WS23xx.xs

filter: Statementstmt 0.0% 0 / 158 Branchbran 0.0% 0 / 80 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 0.0% 0 / 238 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« blib/lib/Device/LaCrosse/WS23xx/MemoryMap.pm ↑ Summary
1 /* -*- c -*-
2 **
3 ** WS23xx.xs - part of Device::LaCrosse::WS23xx
4 **
5 ** Almost all the code in here was shamelessly stolen from Open2300:
6 **
7 ** http://www.lavrsen.dk/twiki/bin/view/Open2300/WebHome
8 **
9 ** Many thanks to Kenneth Lavrsen for writing such useful code,
10 ** and especially for documenting it.
11 */
12  
13 #include <fcntl.h>
14 #include <sys/file.h>
15 #include <termios.h>
16 #include <unistd.h>
17  
18 #include "EXTERN.h"
19 #include "perl.h"
20 #include "XSUB.h"
21  
22 typedef unsigned char uchar;
23 typedef unsigned short ushort;
24  
25 /*
26 ** For debugging: trace all serial I/O to this file
27 */
28 char *trace_path;
29 FILE *trace_fh;
30  
31 void
32 0 trace(char *leader, uchar *buf, uchar byte_count, char *rest)
33 {
34 int i;
35  
36 // No trace file defined: do nothing
37 0 ▶ if (! trace_path) {
Branch: 1 branch
BranchTrueFalseTotal
if (! trace_path) { 0 0 0
38 0 return;
39 }
40  
41 // First time through: open the trace file for writing
42 0 ▶ if (!trace_fh) {
Branch: 1 branch
BranchTrueFalseTotal
if (!trace_fh) { 0 0 0
43 0 trace_fh = fopen(trace_path, "w");
44 }
45 0 fprintf(trace_fh, leader);
46 0 ▶ for (i=0; i < byte_count; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i < byte_count; i++) { 0 0 0
47 0 fprintf(trace_fh, " %02X", buf[i]);
48 }
49 0 ▶ if (rest)
Branch: 1 branch
BranchTrueFalseTotal
if (rest) 0 0 0
50 0 fprintf(trace_fh,rest);
51 0 fprintf(trace_fh,"\n");
52 0 fflush(trace_fh);
53 }
54  
55  
56  
57 /*
58 ** address_encoder
59 **
60 ** Generates the addressing bytes used to tell the WS-23xx
61 ** what address we want.
62 */
63 uchar
64 0 address_encoder(ushort address, uchar index)
65 {
66 /*
67 ** For a given short 0x1234, there are four nybbles to send.
68 ** Thus index goes from 0 to 3, where 0 is the highest-order
69 ** nybble ('1' in 1234) and 3 is the lowest ('4' in 1234).
70 **
71 ** Extract that nybble and 'embed' it into the middle of 0x82.
72 ** That is: shift it left by two, and OR it in. Binary view:
73 **
74 ** 0x82 = 1000 0010
75 ** nybble = nn nn
76 ** result = 10nn nn10
77 */
78 0 uchar nybble = (address >> (4 * (3 - index))) & 0x0F;
79  
80 0 return 0x82 | (nybble << 2);
81 }
82  
83  
84 uchar
85 0 bytecount_encoder(uchar bytecount)
86 {
87 0 return 0xC2 | ((bytecount & 0xF) << 2);
88 }
89  
90 uchar
91 0 address_response(ushort address, uchar index)
92 {
93 0 uchar nybble = (address >> (4 * (3 - index))) & 0x0F;
94  
95 0 return (index << 4) | nybble;
96 }
97  
98 uchar
99 0 bytecount_response(uchar bytecount)
100 {
101 0 return 0x30 | (bytecount & 0xF);
102 }
103  
104  
105  
106 /********************************************************************
107 * data_encoder converts up to 15 data bytes to the form needed
108 * by the WS-2300 when sending write commands.
109 *
110 * Input: number - number of databytes (integer)
111 * encode_constant - unsigned char
112 * 0x12=set bit, 0x32=unset bit, 0x42=write nibble
113 * data_in - char array with up to 15 hex values
114 *
115 * Output: address_out - Pointer to an unsigned character array.
116 *
117 * Returns: Nothing.
118 *
119 ********************************************************************/
120 0 void data_encoder(int number, uchar encode_constant,
121 uchar *data_in, uchar *data_out)
122 {
123 0 int i = 0;
124  
125 0 ▶ for (i = 0; i < number; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < number; i++) 0 0 0
126 {
127 0 data_out[i] = (uchar) (encode_constant + (data_in[i] * 4));
128 }
129  
130 0 return;
131 }
132  
133  
134 /********************************************************************
135 * numberof_encoder converts the number of bytes we want to read
136 * to the form needed by the WS-2300 when sending commands.
137 *
138 * Input: number interger, max value 15
139 *
140 * Returns: unsigned char which is the coded number of bytes
141 *
142 ********************************************************************/
143 unsigned char
144 0 numberof_encoder(uchar number)
145 {
146 0 return (uchar) (0xC2 | (number<<2));
147 }
148  
149  
150 /********************************************************************
151 * command_check0123 calculates the checksum for the first 4
152 * commands sent to WS2300.
153 *
154 * Input: pointer to char to check
155 * sequence of command - i.e. 0, 1, 2 or 3.
156 *
157 * Returns: calculated checksum as unsigned char
158 *
159 ********************************************************************/
160 uchar
161 0 command_check0123(uchar *command, int sequence)
162 {
163 int response;
164  
165 0 response = sequence * 16 + ((*command) - 0x82) / 4;
166  
167 0 return (uchar) response;
168 }
169  
170  
171 /********************************************************************
172 * command_check4 calculates the checksum for the last command
173 * which is sent just before data is received from WS2300
174 *
175 * Input: number of bytes requested
176 *
177 * Returns: expected response from requesting number of bytes
178 *
179 ********************************************************************/
180 uchar
181 0 command_check4(int number)
182 {
183 int response;
184  
185 0 response = 0x30 + number;
186  
187 0 return response;
188 }
189  
190  
191 /********************************************************************
192 * data_checksum calculates the checksum for the data bytes received
193 * from the WS2300
194 *
195 * Input: pointer to array of data to check
196 * number of bytes in array
197 *
198 * Returns: calculated checksum as unsigned char
199 *
200 ********************************************************************/
201 uchar
202 0 data_checksum(uchar *data, uchar byte_count)
203 {
204 int i;
205 0 unsigned int checksum = 0;
206  
207 0 ▶ for (i = 0; i < byte_count; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < byte_count; i++) { 0 0 0
208 0 checksum += data[i];
209 }
210  
211 0 return checksum & 0xFF;
212 }
213  
214  
215  
216  
217  
218  
219 0 int read_device(int fh, uchar *buffer, int size)
220 {
221 0 int bytes_read = 0;
222  
223 0 ▶ while (bytes_read < size) {
Branch: 1 branch
BranchTrueFalseTotal
while (bytes_read < size) { 0 0 0
224 0 int ret = read(fh, buffer+bytes_read, size-bytes_read);
225 0 ▶ if (ret < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (ret < 0) 0 0 0
226 0 continue;
227  
228 0 ▶ if (ret == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret == 0) { 0 0 0
229 // Nothing read. Wait up to 1 second for more data.
230 fd_set readfd;
231 0 struct timeval timeout = { 1, 0 };
232  
233 0 ▶ FD_ZERO(&readfd);
Branch: 1 branch
BranchTrueFalseTotal
FD_ZERO(&readfd); 0 0 0
234 0 FD_SET(fh, &readfd);
235  
236 0 ▶ if (! select(fh+1, &readfd, 0, 0, &timeout)) {
Branch: 1 branch
BranchTrueFalseTotal
if (! select(fh+1, &readfd, 0, 0, &timeout)) { 0 0 0
237 // Timed out with nothing to read. Abort.
238 #ifdef DEBUG
239 fprintf(stderr,"Yuk. Read %d of %d bytes.\n",bytes_read,size);
240 #endif
241 0 trace("<-", 0, 0, "timed out");
242 0 return bytes_read;
243 }
244  
245 // select() says there's more to read
246 }
247 else {
248 0 trace("<-", buffer+bytes_read, ret, 0);
249 }
250  
251 0 bytes_read += ret;
252 }
253  
254 // Yay!
255 0 return bytes_read;
256 }
257  
258  
259  
260 int
261 0 write_device(int fh, uchar *buffer, int size)
262 {
263 0 int ret = write(fh, buffer, size);
264  
265 0 ▶ trace("->", buffer, size, (ret==size ? 0 : "*ERR*"));
Branch: 1 branch
BranchTrueFalseTotal
trace("->", buffer, size, (ret==size ? 0 : "*ERR*")); 0 0 0
266  
267 0 ▶ if (ret != size) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret != size) { 0 0 0
268 0 fprintf(stderr,"write failed: size=%d ret=%d errno=%d\n",
269 0 size,ret,errno);
270 }
271 0 tcdrain(fh); // wait for all output written
272 0 return ret;
273 }
274  
275  
276 int
277 0 write_readback(int fh, uchar byte, uchar expect)
278 {
279 int i;
280 uchar readback;
281  
282 /*
283 ** The WS-23xx seems to sometimes miss its input. That is,
284 ** we send something but it's never received. If we time out
285 ** on receiving the acknowledgment, retry the send. Mistakes
286 ** are unlikely due to the nature of the protocol.
287 */
288 0 ▶ for (i=0; i < 2; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i < 2; i++) { 0 0 0
289 0 ▶ if (write_device(fh, &byte, 1) != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (write_device(fh, &byte, 1) != 1) { 0 0 0
290 #if DEBUG
291 fprintf(stderr,"Error writing byte[%X]\n", byte);
292 #endif
293 0 return -1;
294 }
295  
296 /*
297 ** If the read is successful, make sure it's what we expect.
298 */
299 0 ▶ if (read_device(fh, &readback, 1) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (read_device(fh, &readback, 1) == 1) { 0 0 0
300 0 ▶ if (readback == expect) {
Branch: 1 branch
BranchTrueFalseTotal
if (readback == expect) { 0 0 0
301 0 return 1;
302 }
303 /* Read something, but it's not what we expected. */
304 #if DEBUG
305 fprintf(stderr,"write_readback: sent %02X, expected %02X, got %02X\n", byte, expect, readback);
306 #endif
307 0 return -1;
308 }
309 }
310  
311 /* Fall through: tried multiple writes, but never got back anything. */
312 #if DEBUG
313 fprintf(stderr,"Error reading byte after sending %02X\n",byte);
314 #endif
315 0 return -1;
316 }
317  
318  
319 0 void _ws_reset(int fh)
320 {
321 0 uchar reset = 0x06;
322 uchar answer;
323 int i;
324 fd_set readfd;
325 0 struct timeval timeout = { 0, 0 };
326  
327 0 trace("--reset--",0,0,0);
328 0 ▶ for (i = 0; i < 10; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 10; i++) { 0 0 0
329 // Discard any garbage in the input buffer
330 0 tcflush(fh, TCIOFLUSH);
331  
332 0 ▶ FD_ZERO(&readfd);
Branch: 1 branch
BranchTrueFalseTotal
FD_ZERO(&readfd); 0 0 0
333 0 FD_SET(fh, &readfd);
334 0 ▶ if (select(fh+1, &readfd, 0, 0, &timeout))
Branch: 1 branch
BranchTrueFalseTotal
if (select(fh+1, &readfd, 0, 0, &timeout)) 0 0 0
335 0 printf("got here: select says there's something to read\n");
336  
337 0 write_device(fh, &reset, 1);
338 // Occasionally 0, then 2 is returned. If zero comes back, continue
339 // reading as this is more efficient than sending an out-of sync
340 // reset and letting the data reads restore synchronization.
341 // Occasionally, multiple 2's are returned. Read with a fast timeout
342 // until all data is exhausted, if we got a two back at all, we
343 // consider it a success
344 0 ▶ while (1 == read_device(fh, &answer, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
while (1 == read_device(fh, &answer, 1)) { 0 0 0
345 0 ▶ if (answer == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (answer == 2) { 0 0 0
346 0 return;
347 }
348 0 ▶ else if (answer != 0) {
Branch: 1 branch
BranchTrueFalseTotal
else if (answer != 0) { 0 0 0
349 // Ignore 0, complain about anything else
350 0 printf("unexpected reply after reset: %X\n", answer);
351 }
352 }
353  
354 // usleep(50000 * i); //we sleep longer and longer for each retry
355 }
356 0 croak("Could not reset WS device");
357 }
358  
359  
360 int
361 0 read_data(int fh, ushort address, uchar byte_count, uchar *readdata)
362 {
363 uchar command[5]; // The command bytes we send
364 uchar expect[5]; // The acknowledgment we expect for each byte
365 int i;
366  
367 // Precompute what we send. That will be five bytes: 4 address bytes,
368 // and one bytecount. Also precompute the expected response to each.
369 0 ▶ for (i=0; i < 4; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i < 4; i++) { 0 0 0
370 0 command[i] = address_encoder( address, i);
371 0 expect[i] = address_response(address, i);
372 }
373 0 command[4] = bytecount_encoder( byte_count);
374 0 expect[4] = bytecount_response(byte_count);
375  
376 // Send them. Make sure the unit acknowledges each byte.
377 0 ▶ for (i = 0; i < 5; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 5; i++) { 0 0 0
378 0 ▶ if (write_readback(fh, command[i], expect[i]) != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (write_readback(fh, command[i], expect[i]) != 1) { 0 0 0
379 0 return -1;
380 }
381 }
382  
383 // Read response, including checksum
384 0 ▶ if (read_device(fh, readdata, byte_count+1) != byte_count+1) {
Branch: 1 branch
BranchTrueFalseTotal
if (read_device(fh, readdata, byte_count+1) != byte_count+1) { 0 0 0
385 #ifdef DEBUG
386 fprintf(stderr,"read_data:read_device(3)\n");
387 #endif
388 0 return -1;
389 }
390  
391 0 ▶ if (readdata[byte_count] != data_checksum(readdata, byte_count)) {
Branch: 1 branch
BranchTrueFalseTotal
if (readdata[byte_count] != data_checksum(readdata, byte_count)) { 0 0 0
392 #ifdef DEBUG
393 fprintf(stderr,"read_data:data_checksum(1)\n");
394 #endif
395 0 return -1;
396 }
397  
398 // Success
399 0 return byte_count;
400 }
401  
402  
403  
404 int
405 0 read_safe(int fh, ushort address, ushort byte_count, uchar *buf)
406 {
407 int i;
408  
409 0 ▶ for (i=0; i < 10; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i < 10; i++) { 0 0 0
410 // If we get the expected number of bytes, we're done.
411 0 ▶ if (read_data(fh, address, byte_count, buf) == byte_count)
Branch: 1 branch
BranchTrueFalseTotal
if (read_data(fh, address, byte_count, buf) == byte_count) 0 0 0
412 0 return 1;
413  
414 // FIXME: warn? Reset?
415 // _ws_reset(fh);
416 0 trace("**",0,0," read_data failed");
417 0 tcflush(fh, TCIOFLUSH);
418 }
419  
420 0 return 0;
421 }
422  
423  
424  
425  
426 MODULE = Device::LaCrosse::WS23xx PACKAGE = Device::LaCrosse::WS23xx
427  
428 void
429 _ws_trace_path(path)
430 char * path
431 CODE:
432 0 trace_path = malloc(strlen(path));
433 0 ▶ if (trace_path == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (trace_path == 0) 0 0 0
434 0 croak("malloc failed");
435 0 strcpy(trace_path,path);
436  
437 int
438 _ws_open(path)
439 char * path
440 INIT:
441 int fh;
442 struct termios adtio;
443 int portstatus, fdflags;
444 PPCODE:
445 //Setup serial port
446 0 ▶ if ((fh = open(path, O_RDWR | O_NONBLOCK | O_SYNC)) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if ((fh = open(path, O_RDWR | O_NONBLOCK | O_SYNC)) < 0) 0 0 0
447 {
448 // fprintf(stderr,"\nUnable to open serial device %s\n", path);
449 0 XSRETURN_UNDEF;
450 }
451  
452 0 ▶ if ( flock(fh, LOCK_EX|LOCK_NB) < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ( flock(fh, LOCK_EX|LOCK_NB) < 0 ) { 0 0 0
453 0 fprintf(stderr,"Serial device is locked by other program\n");
454 0 close(fh);
455 0 XSRETURN_UNDEF;
456 }
457  
458 0 if ((fdflags = fcntl(fh, F_GETFL)) == -1 ||
459 0 fcntl(fh, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
460 {
461 0 perror("couldn't reset non-blocking mode");
462 0 exit(EXIT_FAILURE);
463 }
464  
465 0 tcgetattr(fh, &adtio);
466  
467 // Serial control options
468 0 adtio.c_cflag &= ~PARENB; // No parity
469 0 adtio.c_cflag &= ~CSTOPB; // One stop bit
470 0 adtio.c_cflag &= ~CSIZE; // Character size mask
471 0 adtio.c_cflag |= CS8; // Character size 8 bits
472 0 adtio.c_cflag |= CREAD; // Enable Receiver
473 0 adtio.c_cflag &= ~HUPCL; // No "hangup"
474 0 adtio.c_cflag &= ~CRTSCTS; // No flowcontrol
475 0 adtio.c_cflag |= CLOCAL; // Ignore modem control lines
476  
477 // Baudrate, for newer systems
478 0 cfsetispeed(&adtio, B2400);
479 0 cfsetospeed(&adtio, B2400);
480  
481 // Serial local options: adtio.c_lflag
482 // Raw input = clear ICANON, ECHO, ECHOE, and ISIG
483 // Disable misc other local features = clear FLUSHO, NOFLSH, TOSTOP, PENDIN, and IEXTEN
484 // So we actually clear all flags in adtio.c_lflag
485 0 adtio.c_lflag = 0;
486  
487 // Serial input options: adtio.c_iflag
488 // Disable parity check = clear INPCK, PARMRK, and ISTRIP
489 // Disable software flow control = clear IXON, IXOFF, and IXANY
490 // Disable any translation of CR and LF = clear INLCR, IGNCR, and ICRNL
491 // Ignore break condition on input = set IGNBRK
492 // Ignore parity errors just in case = set IGNPAR;
493 // So we can clear all flags except IGNBRK and IGNPAR
494 0 adtio.c_iflag = IGNBRK|IGNPAR;
495  
496 // Serial output options
497 // Raw output should disable all other output options
498 0 adtio.c_oflag &= ~OPOST;
499  
500 0 adtio.c_cc[VTIME] = 10; // timer 1s
501 0 adtio.c_cc[VMIN] = 0; // blocking read until 1 char
502  
503 0 ▶ if (tcsetattr(fh, TCSANOW, &adtio) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (tcsetattr(fh, TCSANOW, &adtio) < 0) 0 0 0
504 {
505 // fprintf(stderr,"Unable to initialize serial device");
506 0 XSRETURN_UNDEF;
507 }
508  
509 0 tcflush(fh, TCIOFLUSH);
510  
511 // Set DTR low and RTS high and leave other ctrl lines untouched
512 0 ioctl(fh, TIOCMGET, &portstatus); // get current port status
513 0 portstatus &= ~TIOCM_DTR;
514 0 portstatus |= TIOCM_RTS;
515 0 ioctl(fh, TIOCMSET, &portstatus); // set current port status
516  
517 // Reset the device, just once
518 0 _ws_reset(fh);
519  
520 // Return the filehandle as a perl scalar
521 0 ▶ XPUSHs(sv_2mortal(newSVnv(fh)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSVnv(fh))); 0 0 0
522  
523 int
524 _ws_close(fh)
525 int fh
526 CODE:
527 0 flock(fh, LOCK_UN);
528 0 RETVAL = close(fh);
529  
530 void
531 _ws_read(fh, addr, nybble_count)
532 int fh
533 unsigned short addr
534 unsigned char nybble_count
535 PREINIT:
536 uchar buf[40];
537 PPCODE:
538 #if DEBUG
539 printf("got here: fh=%d addr=%04X nybbles=%d\n",fh,addr,nybble_count);
540 #endif
541 0 ▶ if (read_safe(fh, addr, (nybble_count+1)/2, buf)) {
Branch: 1 branch
BranchTrueFalseTotal
if (read_safe(fh, addr, (nybble_count+1)/2, buf)) { 0 0 0
542 int i;
543  
544 0 ▶ for (i=0; i < nybble_count; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i < nybble_count; i += 2) { 0 0 0
545 0 ▶ XPUSHs(sv_2mortal(newSVnv(buf[i/2] & 0x0F)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSVnv(buf[i/2] & 0x0F))); 0 0 0
546 0 ▶ if (i < nybble_count-1)
Branch: 1 branch
BranchTrueFalseTotal
if (i < nybble_count-1) 0 0 0
547 0 ▶ XPUSHs(sv_2mortal(newSVnv(buf[i/2] >> 4)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSVnv(buf[i/2] >> 4))); 0 0 0
548 }
549 }
550 else {
551 0 croak("read_safe failed");
552 }
« blib/lib/Device/LaCrosse/WS23xx/MemoryMap.pm ↑ Summary