Repository navigation
Expand file tree
/
Copy pathTheBigLEDowSPI.cpp
More file actions
492 lines (426 loc) · 14.9 KB
/
Copy pathTheBigLEDowSPI.cpp
File metadata and controls
492 lines (426 loc) · 14.9 KB
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <inttypes.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <fcntl.h> // Needed for SPI port
#include <linux/spi/spidev.h> // Needed for SPI port
#include <iostream>
#include <fstream>
#include <experimental/filesystem>
using namespace std;
namespace fs = std::experimental::filesystem::v1;
//-----------------------------------------------------------------------------
// TheBigLEDowSPI.cpp V2.3
//-----------------------------------------------------------------------------
#define VERSION "V2.3"
// ID Utilities ---------------------------------------------------------------
string getMacFromFile(string fname)
{
string mac = "";
ifstream infile(fname);
getline(infile,mac);
// remove ":"
while(mac.find(":")!=string::npos) mac.replace(mac.find(":"),1,"");
return mac;
}
string getMacAddress(string if_n="")
{
#ifndef HAS_SPI
return "1234";
#endif
string path = "/sys/class/net/";
string if_l = "";
string mac = "";
for (auto & p : fs::directory_iterator(path)) {
if_l = p.path().string().substr(15,2);
if(if_l!="lo") {
if(if_l==if_n) {
return getMacFromFile(p.path().string()+"/address");
} else if(mac=="") {
mac=getMacFromFile(p.path().string()+"/address");
}
}
}
return mac;
}
// SPI Utilities --------------------------------------------------------------
int spiOpen( string device, uint32_t speed )
{
int status = -1;
//----- SET SPI MODE -----
//SPI_MODE_0 (0,0) CPOL = 0, CPHA = 0, Clock _idle low, data is clocked in on rising edge, output data (change) on falling edge
//SPI_MODE_1 (0,1) CPOL = 0, CPHA = 1, Clock _idle low, data is clocked in on falling edge, output data (change) on rising edge
//SPI_MODE_2 (1,0) CPOL = 1, CPHA = 0, Clock _idle high, data is clocked in on falling edge, output data (change) on rising edge
//SPI_MODE_3 (1,1) CPOL = 1, CPHA = 1, Clock _idle high, data is clocked in on rising, edge output data (change) on falling edge
uint8_t mode = SPI_MODE_0;
uint8_t bitsPerWord = 8;
int fd = open(device.c_str(), O_RDWR);
if (fd < 0)
{
cerr << "<spiOpen> ERROR : Could not open SPI device." << endl;
exit(1);
}
status = ioctl(fd, SPI_IOC_WR_MODE, &mode);
if(status < 0)
{
cerr << "<spiOpen> ERROR : Could not set SPIMode (WR)...ioctl fail" << endl;
exit(1);
}
status = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bitsPerWord);
if(status < 0)
{
cerr << "<spiOpen> ERROR : Could not set SPI bitsPerWord (WR)...ioctl fail" << endl;
exit(1);
}
status = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
if(status < 0)
{
cerr << "<spiOpen> ERROR : Could not set SPI speed (WR)...ioctl fail" << endl;
exit(1);
}
return( fd );
}
int spiWrite( int fd, uint32_t speed, uint8_t *data, int size )
{
struct spi_ioc_transfer tr;
memset(&tr, 0, sizeof tr);
tr.tx_buf = (unsigned long) data;
tr.rx_buf = (unsigned long) NULL;
tr.len = (unsigned long) size;
tr.speed_hz = speed;
tr.bits_per_word = 8;
try
{
ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
}
catch (const std::exception& e)
{
cerr << "<spiWrite> ERROR : " << e.what() << endl;
}
return 0;
}
// TCP Utilities --------------------------------------------------------------
int tcpConnect(string address, int port)
{
struct sockaddr_in server;
int reuse = 1;
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1)
{
cerr << "tcpConnect> ERROR : Could not create socket (" << strerror(errno) << ")" << endl;
return -1;
}
else
cerr << "tcpConnect> Socket created" << endl;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
cerr << "Could not set SO_REUSEADDR" << endl;
return -1;
}
#ifdef SO_REUSEPORT
if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse)) < 0)
{
cerr << "Could not set SO_REUSEPORT" << endl;
return -1;
}
#endif
if(inet_addr(address.c_str()) < 0)
{
struct hostent *he;
struct in_addr **addr_list;
if((he = gethostbyname(address.c_str())) == NULL)
{
cerr << "tcpConnect> ERROR Gethostbyname : Failed to resolve hostname" << endl;
return -1;
}
addr_list = (struct in_addr **) he->h_addr_list;
for(int i = 0; addr_list[i] != NULL; i++)
{
server.sin_addr = *addr_list[i];
cerr << address << "tcpConnect> resolved to " << inet_ntoa(*addr_list[i]) << endl;
break;
}
}
else
{
server.sin_addr.s_addr = inet_addr( address.c_str() );
}
server.sin_family = AF_INET;
server.sin_port = htons( port );
if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
{
cerr << "tcpConnect> ERROR : connect failed." << endl;
return -1;
}
cerr << "tcpConnect> OK: Connected." << endl;
return sock;
}
// CLIENT ---------------------------------------------------------------------
void send2spi( int fd, uint32_t freq, uint8_t brightness, char *data, int size, bool endFrame )
{
uint8_t light = 224 + (uint8_t) (brightness * 31.0 / 100.0);
uint32_t lgB = (uint32_t) (size * 4 / 3) + 4;
lgB += (endFrame) ? ((uint32_t)((size/3)-1)/16) : 0;
#ifdef HAS_SPI
uint32_t i = 0;
uint8_t buffer[lgB];
for(; i<4; i++)
{
buffer[i] = (uint8_t) 0;
}
for(int j=0; j<size; i+=4, j+=3)
{
buffer[i] = (uint8_t) light;
buffer[i+1] = (uint8_t) data[j];
buffer[i+2] = (uint8_t) data[j+1];
buffer[i+3] = (uint8_t) data[j+2];
}
for(; i<lgB; i++)
{
buffer[i] = (uint8_t) 0;
}
spiWrite( fd, freq, buffer, lgB );
#endif
#ifdef DEBUG
cerr << "<send2spi> data size = " << size << ", spi size = " << lgB << ", light = " << (int)light << endl;
#ifdef HAS_SPI
cerr << "SPI BUFFER[" << sizeof(buffer)/sizeof(*buffer) << "], 20 first bytes : ";
for(int k=4; k<24; k++)
cerr << (int)buffer[k] << ",";
cerr << endl;
#endif
#endif
}
bool isNewFrame( char *header, int lgH, char *buffer, int lgB )
{
if(lgH > lgB)
return false;
for(int i=0; i<lgH; i++)
if(header[i] != buffer[i])
return false;
return true;
}
void tcpClient( int sockFd, int spiFd, uint32_t spiFreq, uint32_t maxSize, uint8_t brightness, char *header, int headerSize, bool endFrame )
{
unsigned int bufferSize = 0;
unsigned int dataSize = maxSize-headerSize;
unsigned int size2receive = maxSize;
int dataLength = 0;
char buffer[maxSize];
char data[maxSize];
while(1)
{
try
{
bufferSize = recv( sockFd, buffer, size2receive, 0 );
if(bufferSize <= 0)
{
cerr << "<tcpClient> ERROR : receive failed." << endl;
break;
}
else
{
if( isNewFrame(header, headerSize, buffer, bufferSize) )
{
if(bufferSize == maxSize)
{
if(dataLength != 0)
{
#ifdef DEBUG
cerr << "<tcpClient> ERROR (buffer == max) : previous frame of " << dataLength << endl;
#endif
}
else
{
memcpy( data, &buffer[headerSize], dataSize ); // copy buffer -> data minus header
send2spi( spiFd, spiFreq, brightness, data, dataSize, endFrame );
#ifdef DEBUG
cerr << "<tcpClient> OK : header frame received in one piece : " << dataSize << " bytes." << endl;
#endif
}
size2receive = maxSize;
dataLength = 0;
}
else
{
if(bufferSize < maxSize)
{
size2receive = maxSize - bufferSize;
dataLength = bufferSize - headerSize;
memcpy( data, &buffer[headerSize], dataLength ); // copy buffer -> data minus header
#ifdef DEBUG
cerr << "<tcpClient> partial header frame received : " << bufferSize << "waiting for " << size2receive << " bytes." << endl;
#endif
}
else
{
size2receive = maxSize;
dataLength = 0;
memset( data, 0, dataSize ); // cleanup data
#ifdef DEBUG
cerr << "<tcpClient> ERROR : header frame too long : " << bufferSize << endl;
#endif
}
}
}
else
{
size2receive -= bufferSize;
if(size2receive == 0)
{
if((dataLength + bufferSize) != dataSize)
{
#ifdef DEBUG
cerr << "<tcpClient> ERROR (size2 == 0) : frame of " << (dataLength + bufferSize) << endl;
#endif
}
else
{
memcpy( &data[dataLength], buffer, bufferSize ); // add buffer to data
send2spi( spiFd, spiFreq, brightness, data, dataSize, endFrame );
#ifdef DEBUG
cerr << "<tcpClient> OK : frame completed from several parts, total : " << dataSize << " bytes." << endl;
#endif
}
size2receive = maxSize;
dataLength = 0;
}
else
{
if(size2receive > 0)
{
if(dataLength == 0)
{
memset( data, 0, dataSize ); // cleanup data
size2receive = maxSize;
dataLength = 0;
#ifdef DEBUG
cerr << "<tcpClient> ERROR : partial frame without Header : " << bufferSize << " bytes." << endl;
#endif
}
else
{
memcpy( &data[dataLength], buffer, bufferSize ); // add buffer to data
dataLength += bufferSize;
#ifdef DEBUG
cerr << "<tcpClient> frame part : " << bufferSize << " bytes received, waiting : " << size2receive << " bytes." << endl;
#endif
}
}
else
{
memset( data, 0, dataSize ); // cleanup data
size2receive = maxSize;
dataLength = 0;
#ifdef DEBUG
cerr << "<tcpClient> ERROR : frame part too long : " << bufferSize << " bytes." << endl;
#endif
}
}
}
}
}
catch (const std::exception& e)
{
cerr << "<tcpClient> ERROR : " << e.what() << endl;
break;
}
}
}
// MAIN -----------------------------------------------------------------------
int main(int argc, char *argv[])
{
char _id[20];
string _ifname = "";
string _host = "127.0.0.1";
int _port = 4200;
string _spiDevice = "/dev/spidev0.0";
char _header[] = { 65, 80, 65, 49, 48, 50, 95 }; // "APA102_"
int _headerSize = sizeof(_header) / sizeof(char);
char _initBuf[80];
// Parameters -----------------------------------------
int _delay = 6;
bool _endFrame = true;
int _countErr = 0;
int _maxCountErr = 100;
// Arguments ------------------------------------------
if ( argc == 1 )
{
cout << "id : id_" << getMacAddress(_ifname) << "_0" << endl;
exit(0);
}
else if ( argc >= 3 )
{
_host = string( argv[1] );
_port = atoi( argv[2] );
if ( argc == 4 ) _spiDevice = string( argv[3] ); // /dev/spidev0.0 /dev/spidev1.0
if ( argc == 5 ) _ifname = string( argv[4] );
strcpy(_id,string( "id_" + getMacAddress() + "_" + _spiDevice.substr(_spiDevice.find_first_of(".")-1,1) ).c_str());
}
else
{
cout << "Usage: " << argv[0] << " host port [spiDevice] [interface]" << endl;
cout << "ie: " << argv[0] << " 127.0.0.1 4200 /dev/spidev0.0 wlan0" << endl;
exit(-1);
}
cerr << "TheBigLEDowSPI (TCP to APA1O2 Client) " << VERSION << ", id : " << _id << ", on : " << _spiDevice << ", waiting for " << _host << ":" << _port << endl;
// Main loop ------------------------------------------
while(1)
{
int sockFd = tcpConnect( _host, _port );
if( sockFd >= 0 )
{
if( send(sockFd, _id, strlen(_id), 0) >= 0 )
{
if( recv(sockFd, _initBuf, sizeof(_initBuf), 0) >= 0 )
{
uint32_t spiFreq = 0;
uint32_t receiveSize = 0;
uint8_t brightness = 0;
int spiFd = 0;
sscanf( _initBuf, "%d,%d,%2" SCNu8, &spiFreq, &receiveSize, &brightness );
spiFreq *= 1000;
if(spiFreq != 0 || receiveSize != 0)
{
#ifdef DEBUG
cerr << "Data transfer parameters received : frequency = " << spiFreq << ", size = " << receiveSize << ", brightness = " << brightness << endl;
#endif
#ifdef HAS_SPI
spiFd = spiOpen( _spiDevice, spiFreq );
#endif
tcpClient( sockFd, spiFd, spiFreq, receiveSize, brightness, _header, _headerSize, _endFrame );
}
else
{
cerr << "<Main> Initialization failed." << endl;
}
#ifdef HAS_SPI
close( spiFd );
#endif
close( sockFd );
sleep( _delay );
}
}
}
else
{
cerr << "<Main> TCP Connect failed." << endl;
}
// after 10 minutes failing to create the socket, we quit
// the process launcher script will relaunch it
_countErr++;
if(_countErr > _maxCountErr) exit( -1 );
sleep( _delay );
}
exit( -1 );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------