source: trunk/csctapi/ifd_smartreader.c@ 1647

Last change on this file since 1647 was 1647, checked in by landlord, 11 years ago

User said that if the timeout is set to 10 seconds (instead of 5) it allows the smartreader to work on IPBox STB

File size: 41.0 KB
Line 
1#if defined(LIBUSB)
2/*
3 ifd_smartreader.c
4 This module provides IFD handling functions for for Argolis smartreader+.
5*/
6
7#include <stdio.h>
8#include <time.h>
9#include <string.h>
10#include"ifd_smartreader.h"
11
12#define OK 0
13#define ERROR 1
14#define LOBYTE(w) ((BYTE)((w) & 0xff))
15#define HIBYTE(w) ((BYTE)((w) >> 8))
16
17//The number of concurrent bulk reads to queue onto the smartreader
18#define NUM_TXFERS 2
19
20typedef struct s_reader S_READER;
21
22static bool smartreader_check_endpoint(libusb_device *usb_dev);
23static struct libusb_device *find_smartreader(const char*busname,const char *devname);
24static void smartreader_init(S_READER *reader);
25static unsigned int smartreader_determine_max_packet_size(S_READER *reader);
26static int smartreader_usb_close_internal (S_READER *reader);
27static int smartreader_usb_reset(S_READER *reader);
28static int smartreader_usb_open_dev(S_READER *reader);
29static int smartreader_usb_purge_rx_buffer(S_READER *reader);
30static int smartreader_usb_purge_tx_buffer(S_READER *reader);
31static int smartreader_usb_purge_buffers(S_READER *reader);
32static int smartreader_convert_baudrate(int baudrate, S_READER *reader, unsigned short *value, unsigned short *index);
33static int smartreader_set_baudrate(S_READER *reader, int baudrate);
34static int smartreader_setdtr_rts(S_READER *reader, int dtr, int rts);
35static int smartreader_setflowctrl(S_READER *reader, int flowctrl);
36static int smartreader_set_line_property2(S_READER *reader, enum smartreader_bits_type bits,
37 enum smartreader_stopbits_type sbit, enum smartreader_parity_type parity,
38 enum smartreader_break_type break_type);
39static int smartreader_set_line_property(S_READER *reader, enum smartreader_bits_type bits,
40 enum smartreader_stopbits_type sbit, enum smartreader_parity_type parity);
41static void smart_flush(S_READER *reader);
42static int smart_read(S_READER *reader, unsigned char* buff, unsigned int size, int timeout_sec);
43static int smartreader_write_data(S_READER *reader, unsigned char *buf, unsigned int size);
44static int smart_write(S_READER *reader, unsigned char* buff, unsigned int size, int udelay);
45static int smartreader_set_latency_timer(S_READER *reader, unsigned short latency);
46static void EnableSmartReader(S_READER *reader, int clock, unsigned short Fi, unsigned char Di, unsigned char Ni, unsigned char T,unsigned char inv, int parity);
47static void ResetSmartReader(S_READER *reader);
48static void *ReaderThread(void *p);
49
50int SR_Init (struct s_reader *reader)
51{
52
53 int ret;
54 char device[128];
55 char *busname;
56 char *devname;
57 char *search = ":";
58 // split the device name from the reader conf into devname and busname
59 memcpy(device,reader->device,128);
60 busname=strtok(device,search);
61 devname=strtok(NULL,search);
62 if(!busname || !devname) {
63 cs_log("Wrong device format (%s), it should be Device=bus:dev",reader->device);
64 return ERROR;
65 }
66
67 cs_debug_mask (D_IFD,"IO:SR: Looking for device %s on bus %s",devname,busname);
68
69 ret = libusb_init(NULL);
70 if (ret < 0) {
71 cs_log("Libusb init error : %d",ret);
72 return ret;
73 }
74
75 smartreader_init(reader);
76
77 reader->sr_config.usb_dev=find_smartreader(busname,devname);
78 if(!reader->sr_config.usb_dev)
79 return ERROR;
80
81 cs_debug_mask (D_IFD,"IO:SR: Opening smartreader device %s on bus %s",devname,busname);
82 //The smartreader has different endpoint addresses
83 //compared to a real FT232 device, so change them here,
84 //also a good way to compare a real FT232 with a smartreader
85 //if you enumarate usb devices
86 reader->sr_config.in_ep = 0x1;
87 reader->sr_config.out_ep = 0x82;
88
89 //open the first smartreader found in the system, this
90 //would need to be changed to an enumerate function
91 //of some sort using the ftdi library. /dev/ttyUSB0 wont exist
92 //as we are accessing the device directly so you will have
93 //to have some other way of addressing the smartreader within
94 //OSCam config files etc...
95 if ((ret=smartreader_usb_open_dev(reader))) {
96 cs_log("unable to open smartreader device %s in bus %s (ret=%d)\n", devname,busname,ret);
97 return ERROR;
98 }
99
100 cs_debug_mask (D_IFD,"IO:SR: Setting smartreader latency timer to 1ms");
101
102 //Set the FTDI latency timer to 1ms
103 ret = smartreader_set_latency_timer(reader, 1);
104
105 //Set databits to 8o2
106 ret = smartreader_set_line_property(reader, BITS_8, STOP_BIT_2, ODD);
107
108 //Set the DTR HIGH and RTS LOW
109 ret=smartreader_setdtr_rts(reader, 0, 0);
110
111 //Disable flow control
112 ret=smartreader_setflowctrl(reader, 0);
113
114 // start the reading thread
115 reader->g_read_buffer_size = 0;
116 reader->modem_status = 0 ;
117 pthread_mutex_init(&reader->g_read_mutex,NULL);
118 pthread_mutex_init(&reader->g_usb_mutex,NULL);
119 ret = pthread_create(&reader->rt, NULL, ReaderThread, (void *)(reader));
120 if (ret) {
121 cs_log("ERROR; return code from pthread_create() is %d", ret);
122 return ERROR;
123 }
124
125 return OK;
126}
127
128
129int SR_GetStatus (struct s_reader *reader, int * in)
130{
131 int state;
132
133 pthread_mutex_lock(&reader->g_read_mutex);
134 state =(reader->modem_status & 0x80) == 0x80 ? 0 : 2;
135 pthread_mutex_unlock(&reader->g_read_mutex);
136
137
138 //state = 0 no card, 1 = not ready, 2 = ready
139 if (state)
140 *in = 1; //CARD, even if not ready report card is in, or it will never get activated
141 else
142 *in = 0; //NOCARD
143
144 return OK;
145}
146
147int SR_Reset (struct s_reader *reader, ATR *atr)
148{
149 unsigned char data[40];
150 int ret;
151 int atr_ok;
152 unsigned int i;
153 int parity[4] = {EVEN, ODD, NONE, EVEN}; // the last EVEN is to try with different F, D values for irdeto card.
154
155 char *parity_str[5]={"NONE", "ODD", "EVEN", "MARK", "SPACE"};
156
157
158 if(reader->mhz==reader->cardmhz && reader->cardmhz*10000 > 3690000)
159 reader->sr_config.fs=reader->cardmhz*10000;
160 else
161 reader->sr_config.fs=3690000;
162
163 ResetSmartReader(reader);
164 for(i=0 ; i < 4 ;i++) {
165 reader->sr_config.irdeto=FALSE;
166 atr_ok=ERROR;
167 memset(data,0,sizeof(data));
168 reader->sr_config.parity=parity[i];
169
170 cs_debug_mask (D_IFD,"IO:SR: Trying with parity %s",parity_str[reader->sr_config.parity]);
171
172
173 // special irdeto case
174 if(i==3) {
175 cs_debug_mask (D_IFD,"IO:SR: Trying irdeto");
176
177 reader->sr_config.F=618; /// magic smartreader value
178 reader->sr_config.D=1;
179 // reader->sr_config.T=2; // will be set to T=1 in EnableSmartReader
180 reader->sr_config.T=1;
181 reader->sr_config.irdeto=TRUE;
182 }
183
184 smart_flush(reader);
185 EnableSmartReader(reader, reader->sr_config.fs/10000, reader->sr_config.F, (BYTE)reader->sr_config.D, reader->sr_config.N, reader->sr_config.T, reader->sr_config.inv,reader->sr_config.parity);
186 sched_yield();
187 cs_sleepms(500); //smartreader in mouse mode needs this, so it might also be needed in native mode.
188
189 //Reset smartcard
190
191 //Set the DTR HIGH and RTS HIGH
192 smartreader_setdtr_rts(reader, 1, 1);
193 // A card with an active low reset is reset by maintaining RST in state L for at least 40 000 clock cycles
194 // so if we have a base freq of 3.5712MHz : 40000/3690000 = .0112007168458781 seconds, aka 11ms
195 // so if we have a base freq of 6.00MHz : 40000/6000000 = .0066666666666666 seconds, aka 6ms
196 // here were doing 200ms .. is it too much ?
197 cs_sleepms(200);
198
199 //Set the DTR HIGH and RTS LOW
200 smartreader_setdtr_rts(reader, 1, 0);
201
202 cs_sleepms(200);
203 sched_yield();
204
205 //Read the ATR
206 ret = smart_read(reader,data, 40,1);
207 cs_debug_mask (D_IFD,"IO:SR: get ATR ret = %d" , ret);
208 if(ret)
209 cs_ddump(data,ATR_MAX_SIZE*2,"IO:SR: ");
210
211 if(data[0]!=0x3B && data[0]!=0x03 && data[0]!=0x3F)
212 continue; // this is not a valid ATR.
213
214 if(data[0]==0x03) {
215 cs_debug_mask (D_IFD,"IO:SR: Inverse convention detected, setting smartreader inv to 1");
216
217 reader->sr_config.inv=1;
218 EnableSmartReader(reader, reader->sr_config.fs/10000, reader->sr_config.F, (BYTE)reader->sr_config.D, reader->sr_config.N, reader->sr_config.T, reader->sr_config.inv,reader->sr_config.parity);
219 }
220 // parse atr
221 if(ATR_InitFromArray (atr, data, ret) == ATR_OK) {
222 cs_debug_mask (D_IFD,"IO:SR: ATR parsing OK");
223 atr_ok=OK;
224 if(i==3) {
225 cs_debug_mask (D_IFD,"IO:SR: Locking F and D for Irdeto mode");
226 reader->sr_config.irdeto=TRUE;
227 }
228 }
229
230 if(atr_ok == OK)
231 break;
232 }
233
234
235 return atr_ok;
236}
237
238int SR_Transmit (struct s_reader *reader, BYTE * buffer, unsigned size)
239
240{
241 unsigned int ret;
242 ret = smart_write(reader, buffer, size, 0);
243 if (ret!=size)
244 return ERROR;
245
246 return OK;
247}
248
249int SR_Receive (struct s_reader *reader, BYTE * buffer, unsigned size)
250{
251 unsigned int ret;
252 ret = smart_read(reader, buffer, size, 1);
253 if (ret!=size)
254 return ERROR;
255
256 return OK;
257}
258
259int SR_WriteSettings (struct s_reader *reader, unsigned short F, BYTE D, BYTE N, BYTE T)
260{
261// maintaining all this admin seems overdone, since after this init the values are nowhere needed
262// reader[ridx].sr_config.F=F;
263// reader[ridx].sr_config.D=D;
264// reader[ridx].sr_config.N=N;
265// reader[ridx].sr_config.T=T;
266// reader->sr_config.fs=reader->mhz*10000; //freq in Hz */
267// EnableSmartReader(reader, reader->sr_config.fs, reader->sr_config.F, (BYTE)reader->sr_config.D, reader->sr_config.N, reader->sr_config.T, reader->sr_config.inv,reader->sr_config.parity);
268
269 // smartreader supports 3.20, 3.43, 3.69, 4.00, 4.36, 4.80, 5.34, 6.00, 6.86, 8.00, 9.61, 12.0, 16.0 Mhz
270 if (reader->mhz >=1600) reader->mhz = 1600; else
271 if (reader->mhz >=1200) reader->mhz = 1200; else
272 if (reader->mhz >=961) reader->mhz = 961; else
273 if (reader->mhz >=800) reader->mhz = 800; else
274 if (reader->mhz >=686) reader->mhz = 686; else
275 if (reader->mhz >=600) reader->mhz = 600; else
276 if (reader->mhz >=534) reader->mhz = 534; else
277 if (reader->mhz >=480) reader->mhz = 480; else
278 if (reader->mhz >=436) reader->mhz = 436; else
279 if (reader->mhz >=400) reader->mhz = 400; else
280 if (reader->mhz >=369) reader->mhz = 369; else
281 if (reader->mhz >=343) reader->mhz = 343; else
282 reader->mhz = 320;
283 EnableSmartReader(reader, reader->mhz, F, D, N, T, reader->sr_config.inv,reader->sr_config.parity);
284
285 //baud rate not really used in native mode since
286 //it's handled by the card, so just set to maximum 3Mb/s
287 smartreader_set_baudrate(reader, 3000000);
288 sched_yield();
289
290 return OK;
291}
292
293int SR_SetParity (struct s_reader *reader)
294{
295 int ret;
296
297 char *parity_str[5]={"NONE", "ODD", "EVEN", "MARK", "SPACE"};
298 cs_debug_mask (D_IFD,"IO:SR: Setting parity to %s",parity_str[reader->sr_config.parity]);
299
300 ret = smartreader_set_line_property(reader, (enum smartreader_bits_type) 8, STOP_BIT_2, reader->sr_config.parity);
301 if(ret)
302 return ERROR;
303
304 sched_yield();
305
306 return OK;
307}
308
309int SR_Close (struct s_reader *reader)
310{
311
312 cs_debug_mask(D_IFD,"IO:SR: Closing smarteader\n");
313
314 reader->sr_config.running=FALSE;
315 pthread_join(reader->rt,NULL);
316 libusb_close(reader->sr_config.usb_dev_handle);
317 libusb_exit(NULL);
318 return OK;
319
320}
321
322
323static void EnableSmartReader(S_READER *reader, int clock, unsigned short Fi, unsigned char Di, unsigned char Ni, unsigned char T, unsigned char inv,int parity) {
324
325 int ret = 0;
326 unsigned char FiDi[4];
327 unsigned short freqk;
328 unsigned char Freq[3];
329 unsigned char N[2];
330 unsigned char Prot[2];
331 unsigned char Invert[2];
332
333 ret = smartreader_set_baudrate(reader, 9600);
334 smartreader_setflowctrl(reader, 0);
335 ret = smartreader_set_line_property(reader, (enum smartreader_bits_type) 5, STOP_BIT_2, NONE);
336
337 // command 1, set F and D parameter
338 if(!reader->sr_config.irdeto) {
339 cs_debug_mask (D_IFD,"IO:SR: sending F=%04X (%d) to smartreader",Fi,Fi);
340 cs_debug_mask (D_IFD,"IO:SR: sending D=%02X (%d) to smartreader",Di,Di);
341 FiDi[0]=0x01;
342 FiDi[1]=HIBYTE(Fi);
343 FiDi[2]=LOBYTE(Fi);
344 FiDi[3]=Di;
345 ret = smart_write(reader,FiDi, sizeof (FiDi),0);
346 }
347 else {
348 cs_log("Not setting F and D as we're in Irdeto mode");
349 }
350
351 // command 2, set the frequency in KHz
352 // direct from the source .. 4MHz is the best init frequency for T=0 card, but looks like it's causing issue with some nagra card, reveting to 3.69MHz
353 freqk = clock * 10; //clock with type int couldnt hold freq in Hz on all platforms, so I reverted to 10khz units (like mhz) - dingo
354 cs_debug_mask (D_IFD,"IO:SR: sending Freq=%04X (%d) to smartreader",freqk,freqk);
355 Freq[0]=0x02;
356 Freq[1]=HIBYTE(freqk);
357 Freq[2]=LOBYTE(freqk);
358 ret = smart_write(reader, Freq, sizeof (Freq),0);
359
360 // command 3, set paramter N
361 cs_debug_mask (D_IFD,"IO:SR: sending N=%02X (%d) to smartreader",Ni,Ni);
362 N[0]=0x03;
363 N[1]=Ni;
364 ret = smart_write(reader, N, sizeof (N),0);
365
366 // command 4 , set parameter T
367 if(reader->sr_config.irdeto) // special trick to get ATR for Irdeto card, we need T=1 at reset, after that oscam takes care of T1 protocol, so we need T=0
368 {
369 T=1;
370 reader->sr_config.T=1;
371 }
372 else if (T==1)
373 T=0; // T=1 protocol is handled by oscam
374
375 cs_debug_mask (D_IFD,"IO:SR: sending T=%02X (%d) to smartreader",T,T);
376 Prot[0]=0x04;
377 Prot[1]=T;
378 ret = smart_write(reader, Prot, sizeof (Prot),0);
379
380 // command 5, set invert y/n
381 cs_debug_mask (D_IFD,"IO:SR: sending inv=%02X to smartreader",inv);
382 Invert[0]=0x05;
383 Invert[1]=inv;
384 ret = smart_write(reader, Invert, sizeof (Invert),0);
385
386 ret = smartreader_set_line_property2(reader, BITS_8, STOP_BIT_2, parity, BREAK_ON);
387 // send break for 350ms, also comes from JoePub debugging.
388 cs_sleepms(350);
389 ret = smartreader_set_line_property2(reader, BITS_8, STOP_BIT_2, parity, BREAK_OFF);
390
391 smart_flush(reader);
392}
393
394static void ResetSmartReader(S_READER *reader)
395{
396
397 smart_flush(reader);
398 // set smartreader+ default values
399 reader->sr_config.F=372;
400 reader->sr_config.D=1.0;
401 if(reader->mhz==reader->cardmhz && reader->cardmhz*10000 > 3690000)
402 reader->sr_config.fs=reader->cardmhz*10000;
403 else
404 reader->sr_config.fs=3690000;
405 reader->sr_config.N=0;
406 reader->sr_config.T=0;
407 reader->sr_config.inv=0;
408
409 EnableSmartReader(reader, reader->sr_config.fs/10000, reader->sr_config.F, (BYTE)reader->sr_config.D, reader->sr_config.N, reader->sr_config.T, reader->sr_config.inv,reader->sr_config.parity);
410 sched_yield();
411
412}
413
414static bool smartreader_check_endpoint(libusb_device *usb_dev)
415{
416 struct libusb_device_descriptor desc;
417 struct libusb_config_descriptor *configDesc;
418 int ret;
419 int j,k,l;
420 uint8_t tmpEndpointAddress;
421 int nb_endpoint_ok;
422
423
424 nb_endpoint_ok=0;
425 ret = libusb_get_device_descriptor(usb_dev, &desc);
426 if (ret < 0) {
427 cs_log("Smartreader : couldn't read device descriptor, assuming this is not a smartreader");
428 return FALSE;
429 }
430 if (desc.bNumConfigurations) {
431 ret=libusb_get_active_config_descriptor(usb_dev,&configDesc);
432 if(ret) {
433 cs_log("Smartreader : couldn't read config descriptor , assuming this is not a smartreader");
434 return FALSE;
435 }
436
437 for(j=0; j<configDesc->bNumInterfaces; j++)
438 for(k=0; k<configDesc->interface[j].num_altsetting; k++)
439 for(l=0; l<configDesc->interface[j].altsetting[k].bNumEndpoints; l++) {
440 tmpEndpointAddress=configDesc->interface[j].altsetting[k].endpoint[l].bEndpointAddress;
441 if((tmpEndpointAddress== 0x1) || (tmpEndpointAddress== 0x82))
442 nb_endpoint_ok++;
443 }
444 }
445 if(nb_endpoint_ok!=2)
446 return FALSE;
447 return TRUE;
448}
449
450
451static struct libusb_device* find_smartreader(const char *busname,const char *devname)
452{
453 int dev_found;
454 libusb_device *dev;
455 libusb_device_handle *usb_dev_handle;
456 libusb_device **devs;
457 ssize_t cnt;
458 int i = 0;
459 int ret;
460 struct libusb_device_descriptor desc;
461
462 cnt = libusb_get_device_list(NULL, &devs);
463 if (cnt < 0)
464 return NULL;
465
466 while ((dev = devs[i++]) != NULL) {
467 dev_found=FALSE;
468 ret = libusb_get_device_descriptor(dev, &desc);
469 if (ret < 0) {
470 cs_log("failed to get device descriptor for device %s on bus %s\n",devname,busname);
471 return NULL;
472 }
473
474 if (desc.idVendor==0x0403 && desc.idProduct==0x6001) {
475 ret=libusb_open(dev,&usb_dev_handle);
476 if (ret) {
477 cs_log ("coulnd't open device %03d:%03d\n", libusb_get_bus_number(dev), libusb_get_device_address(dev));
478 continue;
479 }
480
481 if(libusb_get_bus_number(dev)==atoi(busname) && libusb_get_device_address(dev)==atoi(devname)) {
482 cs_debug_mask(D_IFD,"IO:SR: Checking FTDI device: %03d on bus %03d",libusb_get_device_address(dev),libusb_get_bus_number(dev));
483 // check for smargo endpoints.
484 if(smartreader_check_endpoint(dev))
485 dev_found=TRUE;
486 }
487
488
489 libusb_close(usb_dev_handle);
490 }
491
492 if (dev_found)
493 break;
494 }
495
496 if(!dev_found) {
497 cs_log("Smartreader device %s:%s not found",busname,devname);
498 return NULL;
499 }
500 else
501 cs_log("Found smartreader device %s:%s",busname,devname);
502
503 return dev;
504}
505
506void smartreader_init(S_READER *reader)
507{
508 reader->sr_config.usb_dev = NULL;
509 reader->sr_config.usb_dev_handle=NULL;
510 reader->sr_config.usb_read_timeout = 10000;
511 reader->sr_config.usb_write_timeout = 10000;
512
513 reader->sr_config.type = TYPE_BM; /* chip type */
514 reader->sr_config.baudrate = -1;
515 reader->sr_config.bitbang_enabled = 0; /* 0: normal mode 1: any of the bitbang modes enabled */
516
517 reader->sr_config.writebuffer_chunksize = 64;
518 reader->sr_config.max_packet_size = 0;
519
520 reader->sr_config.interface = INTERFACE_ANY;
521 reader->sr_config.index = INTERFACE_A;
522 reader->sr_config.in_ep = 0x02;
523 reader->sr_config.out_ep = 0x82;
524}
525
526
527static unsigned int smartreader_determine_max_packet_size(S_READER *reader)
528{
529 unsigned int packet_size;
530 struct libusb_device_descriptor desc;
531 struct libusb_config_descriptor *configDesc;
532 struct libusb_interface interface;
533 struct libusb_interface_descriptor intDesc;
534
535 int ret;
536 // Determine maximum packet size. Init with default value.
537 // New hi-speed devices from FTDI use a packet size of 512 bytes
538 // but could be connected to a normal speed USB hub -> 64 bytes packet size.
539 if (reader->sr_config.type == TYPE_2232H || reader->sr_config.type == TYPE_4232H)
540 packet_size = 512;
541 else
542 packet_size = 64;
543
544 ret = libusb_get_device_descriptor(reader->sr_config.usb_dev, &desc);
545 if (ret < 0) {
546 cs_log("Smartreader : couldn't read device descriptor , using default packet size");
547 return packet_size;
548 }
549 if (desc.bNumConfigurations)
550 {
551 ret=libusb_get_active_config_descriptor(reader->sr_config.usb_dev,&configDesc);
552 if(ret) {
553 cs_log("Smartreader : couldn't read config descriptor , using default packet size");
554 return packet_size;
555 }
556
557 if (reader->sr_config.interface < configDesc->bNumInterfaces)
558 {
559 interface=configDesc->interface[reader->sr_config.interface];
560 if (interface.num_altsetting > 0)
561 {
562 intDesc = interface.altsetting[0];
563 if (intDesc.bNumEndpoints > 0)
564 {
565 packet_size = intDesc.endpoint[0].wMaxPacketSize;
566 }
567 }
568 }
569 }
570
571 return packet_size;
572}
573
574
575static int smartreader_usb_close_internal (S_READER *reader)
576{
577 int ret = 0;
578
579 if (reader->sr_config.usb_dev_handle)
580 {
581 libusb_close (reader->sr_config.usb_dev_handle);
582 reader->sr_config.usb_dev_handle=NULL;
583 }
584
585 return ret;
586}
587
588
589int smartreader_usb_reset(S_READER *reader)
590{
591 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
592 FTDI_DEVICE_OUT_REQTYPE,
593 SIO_RESET_REQUEST,
594 SIO_RESET_SIO,
595 reader->sr_config.index,
596 NULL,
597 0,
598 reader->sr_config.usb_write_timeout) != 0) {
599 cs_log("Smartreader reset failed");
600 return (-1);
601 }
602
603 // Invalidate data in the readbuffer
604 // ftdi->readbuffer_offset = 0;
605 // ftdi->readbuffer_remaining = 0;
606
607 return 0;
608}
609
610
611int smartreader_usb_open_dev(S_READER *reader)
612{
613 int detach_errno = 0;
614 struct libusb_device_descriptor desc;
615 int ret;
616
617#ifdef __WIN32__
618 int config;
619 int config_val = 1;
620#endif
621
622 ret=libusb_open(reader->sr_config.usb_dev,&reader->sr_config.usb_dev_handle);
623 if (ret) {
624 cs_log("Smartreader usb_open() failed");
625 return (-4);
626 }
627#if defined(OS_LINUX)
628 // Try to detach smartreader_sio kernel module.
629 // Returns ENODATA if driver is not loaded.
630 //
631 // The return code is kept in a separate variable and only parsed
632 // if usb_set_configuration() or usb_claim_interface() fails as the
633 // detach operation might be denied and everything still works fine.
634 // Likely scenario is a static smartreader_sio kernel module.
635 if (libusb_detach_kernel_driver(reader->sr_config.usb_dev_handle, reader->sr_config.interface) != 0 && errno != ENODATA) {
636 detach_errno = errno;
637 cs_log("Couldn't detach interface from kernel. Please unload the FTDI drivers");
638 return(LIBUSB_ERROR_NOT_SUPPORTED);
639 }
640#endif
641 ret = libusb_get_device_descriptor(reader->sr_config.usb_dev, &desc);
642
643#ifdef __WIN32__
644 // set configuration (needed especially for windows)
645 // tolerate EBUSY: one device with one configuration, but two interfaces
646 // and libftdi sessions to both interfaces (e.g. FT2232)
647
648 if (desc.bNumConfigurations > 0)
649 {
650 ret=libusb_get_configuration(reader->sr_config.usb_dev_handle,&config);
651
652 // libusb-win32 on Windows 64 can return a null pointer for a valid device
653 if (libusb_set_configuration(reader->sr_config.usb_dev_handle, config) &&
654 errno != EBUSY)
655 {
656 smartreader_usb_close_internal (reader);
657 if (detach_errno == EPERM) {
658 cs_log("inappropriate permissions on device!");
659 return(-8);
660 }
661 else {
662 cs_log("unable to set usb configuration. Make sure smartreader_sio is unloaded!");
663 return (-3);
664 }
665 }
666 }
667#endif
668
669 ret=libusb_claim_interface(reader->sr_config.usb_dev_handle, reader->sr_config.interface) ;
670 if (ret!= 0)
671 {
672 smartreader_usb_close_internal (reader);
673 if (detach_errno == EPERM) {
674 cs_log("inappropriate permissions on device!");
675 return (-8);
676 }
677 else {
678 cs_log("unable to claim usb device. Make sure smartreader_sio is unloaded!");
679 return (-5);
680 }
681 }
682
683 if (smartreader_usb_reset (reader) != 0) {
684 smartreader_usb_close_internal (reader);
685 cs_log("smartreader_usb_reset failed");
686 return (-6);
687 }
688
689 // Try to guess chip type
690 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
691 if (desc.bcdDevice == 0x400 || (desc.bcdDevice == 0x200
692 && desc.iSerialNumber == 0))
693 reader->sr_config.type = TYPE_BM;
694 else if (desc.bcdDevice == 0x200)
695 reader->sr_config.type = TYPE_AM;
696 else if (desc.bcdDevice == 0x500)
697 reader->sr_config.type = TYPE_2232C;
698 else if (desc.bcdDevice == 0x600)
699 reader->sr_config.type = TYPE_R;
700 else if (desc.bcdDevice == 0x700)
701 reader->sr_config.type = TYPE_2232H;
702 else if (desc.bcdDevice == 0x800)
703 reader->sr_config.type = TYPE_4232H;
704
705 // Set default interface on dual/quad type chips
706 switch(reader->sr_config.type) {
707 case TYPE_2232C:
708 case TYPE_2232H:
709 case TYPE_4232H:
710 if (!reader->sr_config.index)
711 reader->sr_config.index = INTERFACE_A;
712 break;
713 default:
714 break;
715 }
716
717 // Determine maximum packet size
718 reader->sr_config.max_packet_size = smartreader_determine_max_packet_size(reader);
719
720 if (smartreader_set_baudrate (reader, 9600) != 0) {
721 smartreader_usb_close_internal (reader);
722 cs_log("set baudrate failed");
723 return (-7);
724 }
725
726 return (0);
727}
728
729
730int smartreader_usb_purge_rx_buffer(S_READER *reader)
731{
732 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
733 FTDI_DEVICE_OUT_REQTYPE,
734 SIO_RESET_REQUEST,
735 SIO_RESET_PURGE_RX,
736 reader->sr_config.index,
737 NULL,
738 0,
739 reader->sr_config.usb_write_timeout) != 0) {
740 cs_log("FTDI purge of RX buffer failed");
741 return (-1);
742 }
743
744
745 return 0;
746}
747
748int smartreader_usb_purge_tx_buffer(S_READER *reader)
749{
750 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
751 FTDI_DEVICE_OUT_REQTYPE,
752 SIO_RESET_REQUEST,
753 SIO_RESET_PURGE_TX,
754 reader->sr_config.index,
755 NULL,
756 0,
757 reader->sr_config.usb_write_timeout) != 0) {
758 cs_log("FTDI purge of TX buffer failed");
759 return (-1);
760 }
761
762 return 0;
763}
764
765int smartreader_usb_purge_buffers(S_READER *reader)
766{
767 int result;
768
769 result = smartreader_usb_purge_rx_buffer(reader);
770 if (result < 0)
771 return -1;
772
773 result = smartreader_usb_purge_tx_buffer(reader);
774 if (result < 0)
775 return -2;
776
777 return 0;
778}
779
780static int smartreader_convert_baudrate(int baudrate, S_READER *reader, unsigned short *value, unsigned short *index)
781{
782 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
783 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
784 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
785 int divisor, best_divisor, best_baud, best_baud_diff;
786 unsigned long encoded_divisor;
787 int i;
788
789 if (baudrate <= 0)
790 {
791 // Return error
792 return -1;
793 }
794
795 divisor = 24000000 / baudrate;
796
797 if (reader->sr_config.type == TYPE_AM)
798 {
799 // Round down to supported fraction (AM only)
800 divisor -= am_adjust_dn[divisor & 7];
801 }
802
803 // Try this divisor and the one above it (because division rounds down)
804 best_divisor = 0;
805 best_baud = 0;
806 best_baud_diff = 0;
807 for (i = 0; i < 2; i++)
808 {
809 int try_divisor = divisor + i;
810 int baud_estimate;
811 int baud_diff;
812
813 // Round up to supported divisor value
814 if (try_divisor <= 8)
815 {
816 // Round up to minimum supported divisor
817 try_divisor = 8;
818 }
819 else if (reader->sr_config.type != TYPE_AM && try_divisor < 12)
820 {
821 // BM doesn't support divisors 9 through 11 inclusive
822 try_divisor = 12;
823 }
824 else if (divisor < 16)
825 {
826 // AM doesn't support divisors 9 through 15 inclusive
827 try_divisor = 16;
828 }
829 else
830 {
831 if (reader->sr_config.type == TYPE_AM)
832 {
833 // Round up to supported fraction (AM only)
834 try_divisor += am_adjust_up[try_divisor & 7];
835 if (try_divisor > 0x1FFF8)
836 {
837 // Round down to maximum supported divisor value (for AM)
838 try_divisor = 0x1FFF8;
839 }
840 }
841 else
842 {
843 if (try_divisor > 0x1FFFF)
844 {
845 // Round down to maximum supported divisor value (for BM)
846 try_divisor = 0x1FFFF;
847 }
848 }
849 }
850 // Get estimated baud rate (to nearest integer)
851 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
852 // Get absolute difference from requested baud rate
853 if (baud_estimate < baudrate)
854 {
855 baud_diff = baudrate - baud_estimate;
856 }
857 else
858 {
859 baud_diff = baud_estimate - baudrate;
860 }
861 if (i == 0 || baud_diff < best_baud_diff)
862 {
863 // Closest to requested baud rate so far
864 best_divisor = try_divisor;
865 best_baud = baud_estimate;
866 best_baud_diff = baud_diff;
867 if (baud_diff == 0)
868 {
869 // Spot on! No point trying
870 break;
871 }
872 }
873 }
874 // Encode the best divisor value
875 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
876 // Deal with special cases for encoded value
877 if (encoded_divisor == 1)
878 {
879 encoded_divisor = 0; // 3000000 baud
880 }
881 else if (encoded_divisor == 0x4001)
882 {
883 encoded_divisor = 1; // 2000000 baud (BM only)
884 }
885 // Split into "value" and "index" values
886 *value = (unsigned short)(encoded_divisor & 0xFFFF);
887 if (reader->sr_config.type == TYPE_2232C || reader->sr_config.type == TYPE_2232H || reader->sr_config.type == TYPE_4232H)
888 {
889 *index = (unsigned short)(encoded_divisor >> 8);
890 *index &= 0xFF00;
891 *index |= reader->sr_config.index;
892 }
893 else
894 *index = (unsigned short)(encoded_divisor >> 16);
895
896 // Return the nearest baud rate
897 return best_baud;
898}
899
900int smartreader_set_baudrate(S_READER *reader, int baudrate)
901{
902 unsigned short value, index;
903 int actual_baudrate;
904
905 if (reader->sr_config.bitbang_enabled)
906 {
907 baudrate = baudrate*4;
908 }
909
910 actual_baudrate = smartreader_convert_baudrate(baudrate, reader, &value, &index);
911 if (actual_baudrate <= 0) {
912 cs_log("Silly baudrate <= 0.");
913 return (-1);
914 }
915
916 // Check within tolerance (about 5%)
917 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
918 || ((actual_baudrate < baudrate)
919 ? (actual_baudrate * 21 < baudrate * 20)
920 : (baudrate * 21 < actual_baudrate * 20))) {
921 cs_log("Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
922 return (-1);
923 }
924
925 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
926 FTDI_DEVICE_OUT_REQTYPE,
927 SIO_SET_BAUDRATE_REQUEST,
928 value,
929 index,
930 NULL,
931 0,
932 reader->sr_config.usb_write_timeout) != 0) {
933 cs_log("Setting new baudrate failed");
934 return (-2);
935 }
936
937 reader->sr_config.baudrate = baudrate;
938 return 0;
939}
940
941int smartreader_setdtr_rts(S_READER *reader, int dtr, int rts)
942{
943 unsigned short usb_val;
944
945 if (dtr)
946 usb_val = SIO_SET_DTR_HIGH;
947 else
948 usb_val = SIO_SET_DTR_LOW;
949
950 if (rts)
951 usb_val |= SIO_SET_RTS_HIGH;
952 else
953 usb_val |= SIO_SET_RTS_LOW;
954
955 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
956 FTDI_DEVICE_OUT_REQTYPE,
957 SIO_SET_MODEM_CTRL_REQUEST,
958 usb_val,
959 reader->sr_config.index,
960 NULL,
961 0,
962 reader->sr_config.usb_write_timeout) != 0) {
963 cs_log("set of rts/dtr failed");
964 return (-1);
965 }
966
967 return 0;
968}
969
970int smartreader_setflowctrl(S_READER *reader, int flowctrl)
971{
972 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
973 FTDI_DEVICE_OUT_REQTYPE,
974 SIO_SET_FLOW_CTRL_REQUEST,
975 0,
976 (flowctrl | reader->sr_config.index),
977 NULL,
978 0,
979 reader->sr_config.usb_write_timeout) != 0) {
980 cs_log("set flow control failed");
981 return (-1);
982 }
983
984 return 0;
985}
986
987int smartreader_set_line_property2(S_READER *reader, enum smartreader_bits_type bits,
988 enum smartreader_stopbits_type sbit, enum smartreader_parity_type parity,
989 enum smartreader_break_type break_type)
990{
991 unsigned short value = bits;
992
993 switch (parity)
994 {
995 case NONE:
996 value |= (0x00 << 8);
997 break;
998 case ODD:
999 value |= (0x01 << 8);
1000 break;
1001 case EVEN:
1002 value |= (0x02 << 8);
1003 break;
1004 case MARK:
1005 value |= (0x03 << 8);
1006 break;
1007 case SPACE:
1008 value |= (0x04 << 8);
1009 break;
1010 }
1011
1012 switch (sbit)
1013 {
1014 case STOP_BIT_1:
1015 value |= (0x00 << 11);
1016 break;
1017 case STOP_BIT_15:
1018 value |= (0x01 << 11);
1019 break;
1020 case STOP_BIT_2:
1021 value |= (0x02 << 11);
1022 break;
1023 }
1024
1025 switch (break_type)
1026 {
1027 case BREAK_OFF:
1028 value |= (0x00 << 14);
1029 break;
1030 case BREAK_ON:
1031 value |= (0x01 << 14);
1032 break;
1033 }
1034
1035 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
1036 FTDI_DEVICE_OUT_REQTYPE,
1037 SIO_SET_DATA_REQUEST,
1038 value,
1039 reader->sr_config.index,
1040 NULL,
1041 0,
1042 reader->sr_config.usb_write_timeout) != 0) {
1043 cs_log("Setting new line property failed");
1044 return (-1);
1045 }
1046
1047 return 0;
1048}
1049
1050
1051int smartreader_set_line_property(S_READER *reader, enum smartreader_bits_type bits,
1052 enum smartreader_stopbits_type sbit, enum smartreader_parity_type parity)
1053{
1054 return smartreader_set_line_property2(reader, bits, sbit, parity, BREAK_OFF);
1055}
1056
1057
1058
1059void smart_flush(S_READER *reader)
1060{
1061
1062 smartreader_usb_purge_buffers(reader);
1063
1064 pthread_mutex_lock(&reader->g_read_mutex);
1065 reader->g_read_buffer_size = 0;
1066 pthread_mutex_unlock(&reader->g_read_mutex);
1067 sched_yield();
1068}
1069
1070static int smart_read(S_READER *reader, unsigned char* buff, unsigned int size, int timeout_sec)
1071{
1072
1073 int ret = 0;
1074 unsigned int total_read = 0;
1075 struct timeval start, now, dif = {0,0};
1076 gettimeofday(&start,NULL);
1077
1078 while(total_read < size && dif.tv_sec < timeout_sec) {
1079 pthread_mutex_lock(&reader->g_read_mutex);
1080
1081 if(reader->g_read_buffer_size > 0) {
1082
1083 ret = reader->g_read_buffer_size > size-total_read ? size-total_read : reader->g_read_buffer_size;
1084 memcpy(buff+total_read,reader->g_read_buffer,ret);
1085 reader->g_read_buffer_size -= ret;
1086
1087 if(reader->g_read_buffer_size > 0){
1088 memcpy(reader->g_read_buffer, reader->g_read_buffer + ret, reader->g_read_buffer_size);
1089 }
1090
1091 total_read+=ret;
1092 }
1093 pthread_mutex_unlock(&reader->g_read_mutex);
1094
1095 gettimeofday(&now,NULL);
1096 timersub(&now, &start, &dif);
1097 struct timespec req_ts;
1098 req_ts.tv_sec = 0;
1099 req_ts.tv_nsec = 50000;
1100 nanosleep (&req_ts, NULL);//behaves better to signals than usleep and sleep
1101 sched_yield();
1102 }
1103 cs_ddump(buff, total_read, "SR IO: Receive: ");
1104
1105
1106 return total_read;
1107}
1108
1109int smartreader_write_data(S_READER *reader, unsigned char *buf, unsigned int size)
1110{
1111 int ret;
1112 int write_size;
1113 unsigned int offset = 0;
1114 int total_written = 0;
1115 int written;
1116
1117 if(size<reader->sr_config.writebuffer_chunksize)
1118 write_size=size;
1119 else
1120 write_size = reader->sr_config.writebuffer_chunksize;
1121
1122 while (offset < size)
1123 {
1124
1125 if (offset+write_size > size)
1126 write_size = size-offset;
1127
1128 ret = libusb_bulk_transfer(reader->sr_config.usb_dev_handle,
1129 reader->sr_config.in_ep,
1130 buf+offset,
1131 write_size,
1132 &written,
1133 reader->sr_config.usb_write_timeout);
1134 if (ret < 0) {
1135 cs_log("usb bulk write failed : ret = %d",ret);
1136 return(ret);
1137 }
1138 cs_ddump(buf+offset, written, "SR IO: Transmit: ");
1139 total_written += written;
1140 offset += write_size;//FIXME shouldnt this be written?
1141 }
1142
1143 return total_written;
1144}
1145
1146static int smartreader_set_latency_timer(S_READER *reader, unsigned short latency)
1147{
1148 unsigned short usb_val;
1149
1150 if (latency < 1) {
1151 cs_log("latency out of range. Only valid for 1-255");
1152 return (-1);
1153 }
1154
1155 usb_val = latency;
1156 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
1157 FTDI_DEVICE_OUT_REQTYPE,
1158 SIO_SET_LATENCY_TIMER_REQUEST,
1159 usb_val,
1160 reader->sr_config.index,
1161 NULL,
1162 0,
1163 reader->sr_config.usb_write_timeout) != 0) {
1164 cs_log("unable to set latency timer");
1165 return (-2);
1166 }
1167
1168 return 0;
1169}
1170
1171static int smart_write(S_READER *reader, unsigned char* buff, unsigned int size, int udelay)
1172{
1173
1174 int ret = 0;
1175 unsigned int idx;
1176
1177 if (udelay == 0) {
1178 ret = smartreader_write_data(reader, buff, size);
1179 if(ret<0) {
1180 cs_debug_mask (D_IFD,"IO:SR: USB write error : %d",ret);
1181 }
1182 }
1183 else {
1184 for (idx = 0; idx < size; idx++) {
1185 if ((ret = smartreader_write_data(reader, &buff[idx], 1)) < 0){
1186 break;
1187 }
1188 struct timespec req_ts;
1189 req_ts.tv_sec = 0;
1190 req_ts.tv_nsec = udelay * 1000;
1191 nanosleep (&req_ts, NULL); //behaves better with signals than usleep
1192 }
1193 }
1194 sched_yield();
1195 return ret;
1196}
1197
1198static void read_callback(struct libusb_transfer *transfer){
1199
1200 struct s_reader *reader = (struct s_reader*)transfer->user_data;
1201 int copy_size;
1202 int ret;
1203
1204 if(transfer->status == LIBUSB_TRANSFER_COMPLETED) {
1205
1206 if(transfer->actual_length > 2) { //FTDI always sends modem status bytes as first 2 chars with the 232BM
1207
1208 pthread_mutex_lock(&reader->g_read_mutex);
1209
1210 if(reader->g_read_buffer_size == sizeof(reader->g_read_buffer)) {
1211 cs_log("IO:SR: buffer full\n");
1212 //if out read buffer is full then delay
1213 //slightly and go around again
1214 ret = libusb_submit_transfer(transfer);
1215 if(ret!=0)
1216 cs_log("IO:SR: submit async transfer failed with error %d\n",ret);
1217 pthread_mutex_unlock(&reader->g_read_mutex);
1218 return;
1219 }
1220
1221 reader->modem_status = transfer->buffer[1];
1222 copy_size = sizeof(reader->g_read_buffer) - reader->g_read_buffer_size > (unsigned int)transfer->actual_length-2 ? (unsigned int)transfer->actual_length-2: sizeof(reader->g_read_buffer) - reader->g_read_buffer_size;
1223 memcpy(reader->g_read_buffer+reader->g_read_buffer_size,transfer->buffer+2,copy_size);
1224 reader->g_read_buffer_size += copy_size;
1225 pthread_mutex_unlock(&reader->g_read_mutex);
1226 }
1227 else {
1228 if(transfer->actual_length==2) {
1229 pthread_mutex_lock(&reader->g_read_mutex);
1230 reader->modem_status=transfer->buffer[1];
1231 pthread_mutex_unlock(&reader->g_read_mutex);
1232 }
1233 }
1234
1235 ret = libusb_submit_transfer(transfer);
1236 sched_yield();
1237
1238 if(ret!=0)
1239 cs_log("IO:SR: submit async transfer failed with error %d\n",ret);
1240
1241 }
1242 else
1243 cs_log("IO:SR: USB bulk read failed with error %d\n",transfer->status);
1244}
1245
1246
1247static void* ReaderThread(void *p)
1248{
1249
1250 struct libusb_transfer* usbt[NUM_TXFERS];
1251 unsigned char usb_buffers[NUM_TXFERS][64];
1252 struct s_reader *reader;
1253 int ret,idx;
1254
1255 reader = (struct s_reader *)p;
1256 reader->sr_config.running=TRUE;
1257
1258 for(idx=0; idx<NUM_TXFERS; idx++) {
1259 usbt[idx] = libusb_alloc_transfer(0);
1260
1261 libusb_fill_bulk_transfer( usbt[idx],
1262 reader->sr_config.usb_dev_handle,
1263 reader->sr_config.out_ep,
1264 usb_buffers[idx],
1265 64,
1266 &read_callback,
1267 p,
1268 0 );
1269
1270 ret = libusb_submit_transfer(usbt[idx]);
1271 }
1272
1273 while(reader->sr_config.running) {
1274 ret = libusb_handle_events(NULL);
1275 if(ret!=0)
1276 cs_log("libusb_handle_events returned with %d\n",ret);
1277 }
1278
1279 pthread_exit(NULL);
1280}
1281
1282#endif // HAVE_LIBUSB && USE_PTHREAD
Note: See TracBrowser for help on using the repository browser.