- fix Building without Nagra not possible at Nagra_Merlin https://trac.streamboard...
[oscam.git] / csctapi / ifd_smartreader.c
blob6e2bbe79e220de6b3757a73e49f3c460d4c1a16f
1 /*
2 ifd_smartreader.c
3 This module provides IFD handling functions for for Argolis smartreader+.
4 */
6 #include "../globals.h"
8 #ifdef CARDREADER_SMART
9 #include <memory.h>
10 #if defined(__FreeBSD__)
11 #include <libusb.h>
12 #else
13 #include <libusb-1.0/libusb.h>
14 #endif
15 #include "../oscam-lock.h"
16 #include "../oscam-string.h"
17 #include "../oscam-time.h"
18 #include "icc_async.h" // atr.h included in icc_async.h
19 #include "ifd_smartreader_types.h"
21 #if defined(__CYGWIN__)
22 #undef OK
23 #undef ERROR
24 #undef LOBYTE
25 #undef HIBYTE
26 #endif
28 #undef OK
29 #undef ERROR
30 #define OK 0
31 #define ERROR 1
32 #define LOBYTE(w) ((unsigned char)((w) & 0xff))
33 #define HIBYTE(w) ((unsigned char)((w) >> 8))
35 #define NUM_TXFERS 2
37 static int8_t init_lock = 0;
39 static CS_MUTEX_LOCK sr_lock;
40 // to debug rdrtype and ftdi chip type string value in logs instead off the enumarated value
41 static const char *const rdrtype_str[6] = { "SR","Infinity", "SRv2", "TripleP1", "TripleP2", "TripleP3" };
42 static const char *const type_str[7] = { "TYPE_AM", "TYPE_BM", "TYPE_2232C", "TYPE_R", "TYPE_2232H", "TYPE_4232H", "TYPE_232H" };
44 struct sr_data
46 int32_t F;
47 float D;
48 int8_t closing;
49 int32_t fs;
50 int32_t N;
51 int32_t T;
52 int32_t inv;
53 int32_t parity;
54 int32_t irdeto;
55 int32_t running;
56 libusb_device *usb_dev;
57 libusb_device_handle *usb_dev_handle;
58 enum smartreader_chip_type type;
59 enum smartreader_rdrtypename rdrtype;
60 uint8_t in_ep;
61 uint8_t out_ep;
62 int32_t index;
63 /** usb read timeout */
64 int32_t usb_read_timeout;
65 /** usb write timeout */
66 int32_t usb_write_timeout;
67 uint32_t writebuffer_chunksize;
68 unsigned char bitbang_enabled;
69 int baudrate;
70 int32_t interface; // 0 ,1 or 2
71 /** maximum packet size. Needed for filtering modem status bytes every n packets. */
72 uint32_t max_packet_size;
73 unsigned char g_read_buffer[4096];
74 uint32_t g_read_buffer_size;
75 pthread_mutex_t g_read_mutex;
76 pthread_cond_t g_read_cond;
77 pthread_mutex_t g_usb_mutex;
78 pthread_cond_t g_usb_cond;
79 int32_t poll;
80 pthread_t rt;
81 struct libusb_transfer *usbt[NUM_TXFERS];
82 unsigned char usb_buffers[NUM_TXFERS][64];
83 unsigned char modem_status;
84 uint16_t tripledelay;
85 int detectstart ;
88 static int32_t init_count;
89 static int32_t current_count;
91 static int32_t smart_read(struct s_reader *reader, unsigned char *buff, uint32_t size, double timeout_ms)
93 struct sr_data *crdr_data = reader->crdr_data;
94 int32_t ret = 0;
95 uint32_t total_read = 0;
96 int64_t gone = 0;
97 struct timeb start, now;
99 cs_ftime(&start);
100 now = start;
101 do {
102 SAFE_MUTEX_LOCK(&crdr_data->g_read_mutex);
104 while(crdr_data->g_read_buffer_size == 0)
106 gone = comp_timeb(&now, &start);
107 if (gone >= timeout_ms)
108 break;
109 struct timespec ts;
110 add_ms_to_timespec(&ts, timeout_ms - gone);
111 SAFE_COND_TIMEDWAIT(&crdr_data->g_read_cond, &crdr_data->g_read_mutex, &ts);
112 cs_ftime(&now);
115 ret = (crdr_data->g_read_buffer_size > size - total_read ? size - total_read : crdr_data->g_read_buffer_size);
116 memcpy(buff + total_read, crdr_data->g_read_buffer, ret);
117 crdr_data->g_read_buffer_size -= ret;
119 if(crdr_data->g_read_buffer_size > 0)
120 { memmove(crdr_data->g_read_buffer, crdr_data->g_read_buffer + ret, crdr_data->g_read_buffer_size); }
122 total_read += ret;
123 SAFE_MUTEX_UNLOCK(&crdr_data->g_read_mutex);
124 cs_ftime(&now);
125 if(ret>0) { cs_ftime(&start); now = start;} // reset timeout calculation again since reader is responsive!
126 } while(total_read < size && comp_timeb(&now, &start) < timeout_ms);
128 rdr_log_dump_dbg(reader, D_DEVICE, buff, total_read, "SR: Receive:");
129 rdr_log_dbg(reader, D_IFD, " used timeout by smartreader %4.2f ms ", timeout_ms);
130 return total_read;
133 static int32_t smart_write(struct s_reader *reader, unsigned char *buff, uint32_t size)
135 struct sr_data *crdr_data = reader->crdr_data;
136 int32_t write_size;
137 uint32_t offset = 0;
138 int32_t total_written = 0;
139 int32_t written;
141 if(size < crdr_data->writebuffer_chunksize)
142 { write_size = size; }
143 else
144 { write_size = crdr_data->writebuffer_chunksize; }
146 while(offset < size)
148 if(offset + write_size > size)
149 { write_size = size - offset; }
151 int32_t ret = libusb_bulk_transfer(crdr_data->usb_dev_handle,
152 crdr_data->in_ep,
153 buff + offset,
154 write_size,
155 &written,
156 crdr_data->usb_write_timeout);
157 if(ret < 0)
159 rdr_log(reader, "usb bulk write failed : ret = %d", ret);
160 return (ret);
162 rdr_log_dump_dbg(reader, D_DEVICE, buff + offset, written, "SR: Transmit:");
163 total_written += written;
164 offset += write_size;
166 return total_written;
169 static bool smartreader_check_endpoint(struct s_reader *rdr, libusb_device *usb_dev, uint8_t in_endpoint, uint8_t out_endpoint)
171 struct libusb_device_descriptor usbdesc;
172 struct libusb_config_descriptor *configDesc;
173 int32_t ret;
174 int32_t j, k, l;
175 uint8_t tmpEndpointAddress;
176 int32_t nb_endpoint_ok;
179 nb_endpoint_ok = 0;
180 ret = libusb_get_device_descriptor(usb_dev, &usbdesc);
181 if(ret < 0)
183 rdr_log(rdr, "Couldn't read device descriptor, assuming this is not a smartreader");
184 return 0;
186 if(usbdesc.bNumConfigurations)
188 ret = libusb_get_active_config_descriptor(usb_dev, &configDesc);
189 if(ret)
191 rdr_log(rdr, "Couldn't read config descriptor, assuming this is not a smartreader");
192 return 0;
195 for(j = 0; j < configDesc->bNumInterfaces; j++)
196 for(k = 0; k < configDesc->interface[j].num_altsetting; k++)
197 for(l = 0; l < configDesc->interface[j].altsetting[k].bNumEndpoints; l++)
199 tmpEndpointAddress = configDesc->interface[j].altsetting[k].endpoint[l].bEndpointAddress;
200 if((tmpEndpointAddress == in_endpoint) || (tmpEndpointAddress == out_endpoint))
201 { nb_endpoint_ok++; }
204 if(nb_endpoint_ok != 2)
206 rdr_log(rdr, "Endpoint check failed, assuming this is not a smartreader");
207 return 0;
209 return 1;
212 static struct libusb_device *find_smartreader(struct s_reader *rdr, const char *busname, const char *dev_name, uint8_t in_endpoint, uint8_t out_endpoint)
214 rdr->smartdev_found = 0;
215 libusb_device *dev;
216 libusb_device_handle *usb_dev_handle;
217 libusb_device **devs;
218 ssize_t cnt;
219 int32_t i = 0;
220 int32_t ret;
221 struct libusb_device_descriptor usbdesc;
223 cnt = libusb_get_device_list(NULL, &devs);
224 if(cnt < 0)
225 { return NULL; }
227 while((dev = devs[i++]) != NULL)
229 rdr->smartdev_found = 0;
230 ret = libusb_get_device_descriptor(dev, &usbdesc);
231 if(ret < 0)
233 rdr_log(rdr, "failed to get device descriptor for device %s on bus %s", dev_name, busname);
234 return NULL;
237 if(usbdesc.idVendor == 0x0403 && (usbdesc.idProduct == 0x6001 || usbdesc.idProduct == 0x6011))
239 ret = libusb_open(dev, &usb_dev_handle);
240 if(ret)
242 rdr_log(rdr, "coulnd't open device %03d:%03d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
243 switch(ret)
245 case LIBUSB_ERROR_NO_MEM:
246 rdr_log(rdr, "libusb_open error LIBUSB_ERROR_NO_MEM : memory allocation failure");
247 break;
248 case LIBUSB_ERROR_ACCESS:
249 rdr_log(rdr, "libusb_open error LIBUSB_ERROR_ACCESS : the user has insufficient permissions");
250 break;
251 case LIBUSB_ERROR_NO_DEVICE:
252 rdr_log(rdr, "libusb_open error LIBUSB_ERROR_NO_DEVICE : the device has been disconnected");
253 break;
254 default:
255 rdr_log(rdr, "libusb_open unknown error : %d", ret);
256 break;
258 continue;
261 // If the device is specified as "Serial:number", check iSerial
262 if(!strcasecmp(busname, "Serial"))
264 char iserialbuffer[128];
265 if(libusb_get_string_descriptor_ascii(usb_dev_handle, usbdesc.iSerialNumber, (unsigned char *)iserialbuffer, sizeof(iserialbuffer)) > 0)
267 if(!strcmp(trim(iserialbuffer), dev_name))
269 rdr_log_dbg(rdr, D_IFD, "Found reader with serial %s at %03d:%03d", dev_name, libusb_get_bus_number(dev), libusb_get_device_address(dev));
270 if(smartreader_check_endpoint(rdr, dev, in_endpoint, out_endpoint)) {
271 if(out_endpoint == 0x82 && in_endpoint == 0x01 && usbdesc.idProduct == 0x6001) { rdr->smart_type = 0; rdr->smartdev_found = 1;} else
272 if(out_endpoint == 0x81 && in_endpoint == 0x01) { rdr->smart_type = 1; rdr->smartdev_found = 2;} else
273 if(out_endpoint == 0x81 && in_endpoint == 0x02 && usbdesc.idProduct == 0x6001) { rdr->smart_type = 2; rdr->smartdev_found = 3;} else
274 if(out_endpoint == 0x81 && in_endpoint == 0x02 && usbdesc.idProduct == 0x6011) { rdr->smart_type = 3; rdr->smartdev_found = 4; rdr->modemstat = 1;} else
275 if(out_endpoint == 0x83 && in_endpoint == 0x04 && usbdesc.idProduct == 0x6011) { rdr->smart_type = 4; rdr->smartdev_found = 5; rdr->modemstat = 1;} else
276 if(out_endpoint == 0x85 && in_endpoint == 0x06 && usbdesc.idProduct == 0x6011) { rdr->smart_type = 5; rdr->smartdev_found = 6; rdr->modemstat = 1;} else
277 rdr->smartdev_found = 0;
282 else if(libusb_get_bus_number(dev) == atoi(busname) && libusb_get_device_address(dev) == atoi(dev_name))
284 rdr_log_dbg(rdr, D_DEVICE, "SR: Checking FTDI device: %03d on bus %03d", libusb_get_device_address(dev), libusb_get_bus_number(dev));
285 // check for smargo endpoints.
286 if(smartreader_check_endpoint(rdr, dev, in_endpoint, out_endpoint)) {
287 if(out_endpoint == 0x82 && in_endpoint == 0x01 && usbdesc.idProduct == 0x6001) { rdr->smart_type = 0; rdr->smartdev_found = 1;} else
288 if(out_endpoint == 0x81 && in_endpoint == 0x01) { rdr->smart_type = 1; rdr->smartdev_found = 2;} else
289 if(out_endpoint == 0x81 && in_endpoint == 0x02 && usbdesc.idProduct == 0x6001) { rdr->smart_type = 2; rdr->smartdev_found = 3;} else
290 if(out_endpoint == 0x81 && in_endpoint == 0x02 && usbdesc.idProduct == 0x6011) { rdr->smart_type = 3; rdr->smartdev_found = 4; rdr->modemstat = 1;} else
291 if(out_endpoint == 0x83 && in_endpoint == 0x04 && usbdesc.idProduct == 0x6011) { rdr->smart_type = 4; rdr->smartdev_found = 5; rdr->modemstat = 1;} else
292 if(out_endpoint == 0x85 && in_endpoint == 0x06 && usbdesc.idProduct == 0x6011) { rdr->smart_type = 5; rdr->smartdev_found = 6; rdr->modemstat = 1;} else
293 rdr->smartdev_found = 0;
296 libusb_close(usb_dev_handle);
299 if(rdr->smartdev_found >= 1)
300 { break; }
303 if(!rdr->smartdev_found)
305 rdr_log(rdr, "Smartreader device %s:%s not found", busname, dev_name);
306 return NULL;
308 else
309 rdr_log_dbg(rdr, D_IFD, "Found smartreader device %s:%s", busname, dev_name);
311 return dev;
314 void smartreader_init(struct s_reader *reader)
316 uint32_t i;
317 struct sr_data *crdr_data = reader->crdr_data;
319 crdr_data->usb_dev = NULL;
320 crdr_data->usb_dev_handle = NULL;
321 crdr_data->usb_read_timeout = 15000;
322 crdr_data->usb_write_timeout = 10000;
324 crdr_data->type = TYPE_BM; /* chip type */
325 crdr_data->baudrate = -1;
326 crdr_data->bitbang_enabled = 0; /* 0: normal mode 1: any of the bitbang modes enabled */
328 crdr_data->writebuffer_chunksize = 4096;
329 crdr_data->max_packet_size = 0;
330 rdr_log_dbg(reader, D_IFD, "initing smartreader type %s", rdrtype_str[crdr_data->rdrtype]);
331 for(i = 0; i < sizeof(reader_types) / sizeof(struct s_reader_types); ++i) {
332 if(reader_types[i].rdrtypename == crdr_data->rdrtype) {
333 crdr_data->in_ep = reader_types[i].in_ep;
334 crdr_data->out_ep = reader_types[i].out_ep;
335 crdr_data->index = reader_types[i].index;
336 crdr_data->interface = reader_types[i].interface;
342 static uint32_t smartreader_determine_max_packet_size(struct s_reader *reader)
344 struct sr_data *crdr_data = reader->crdr_data;
345 uint32_t packet_size;
346 struct libusb_device_descriptor usbdesc;
347 struct libusb_config_descriptor *configDesc;
348 struct libusb_interface interface;
349 struct libusb_interface_descriptor intDesc;
351 int32_t ret;
352 // Determine maximum packet size. Init with default value.
353 // New hi-speed devices from FTDI use a packet size of 512 bytes
354 // but could be connected to a normal speed USB hub -> 64 bytes packet size.
355 // rdr_log(reader,"DE PACKET SIZE DETERMINATION USES READER TYPE %u", crdr_data->type);
356 if(crdr_data->type == TYPE_2232H || crdr_data->type == TYPE_4232H)
358 packet_size = 512;
360 else
361 { packet_size = 64; }
363 ret = libusb_get_device_descriptor(crdr_data->usb_dev, &usbdesc);
364 if(ret < 0)
366 rdr_log(reader, "Couldn't read device descriptor, using default packet size");
367 return packet_size;
369 if(usbdesc.bNumConfigurations)
371 ret = libusb_get_active_config_descriptor(crdr_data->usb_dev, &configDesc);
372 if(ret)
374 rdr_log(reader, "Couldn't read config descriptor, using default packet size");
375 return packet_size;
378 if(crdr_data->interface < configDesc->bNumInterfaces)
380 interface = configDesc->interface[crdr_data->interface];
381 if(interface.num_altsetting > 0)
383 intDesc = interface.altsetting[0];
384 if(intDesc.bNumEndpoints > 0)
386 packet_size = intDesc.endpoint[0].wMaxPacketSize;
391 return packet_size;
395 static int32_t smartreader_usb_close_internal(struct s_reader *reader)
397 struct sr_data *crdr_data = reader->crdr_data;
398 int32_t ret = 0;
400 if(crdr_data->usb_dev_handle)
402 libusb_close(crdr_data->usb_dev_handle);
403 crdr_data->usb_dev_handle = NULL;
406 return ret;
410 static int32_t smartreader_usb_reset(struct s_reader *reader)
412 struct sr_data *crdr_data = reader->crdr_data;
413 if(libusb_control_transfer(crdr_data->usb_dev_handle,
414 FTDI_DEVICE_OUT_REQTYPE,
415 SIO_RESET_REQUEST,
416 SIO_RESET_SIO,
417 crdr_data->index,
418 NULL,
420 crdr_data->usb_write_timeout) != 0)
422 rdr_log(reader, "Smartreader reset failed");
423 return (-1);
426 return 0;
430 static int32_t smartreader_usb_purge_rx_buffer(struct s_reader *reader)
432 struct sr_data *crdr_data = reader->crdr_data;
433 if(libusb_control_transfer(crdr_data->usb_dev_handle,
434 FTDI_DEVICE_OUT_REQTYPE,
435 SIO_RESET_REQUEST,
436 SIO_RESET_PURGE_RX,
437 crdr_data->index,
438 NULL,
440 crdr_data->usb_write_timeout) != 0)
442 rdr_log(reader, "FTDI purge of RX buffer failed");
443 return (-1);
447 return 0;
450 static int32_t smartreader_usb_purge_tx_buffer(struct s_reader *reader)
452 struct sr_data *crdr_data = reader->crdr_data;
453 if(libusb_control_transfer(crdr_data->usb_dev_handle,
454 FTDI_DEVICE_OUT_REQTYPE,
455 SIO_RESET_REQUEST,
456 SIO_RESET_PURGE_TX,
457 crdr_data->index,
458 NULL,
460 crdr_data->usb_write_timeout) != 0)
462 rdr_log(reader, "FTDI purge of TX buffer failed");
463 return (-1);
466 return 0;
469 static int32_t smartreader_usb_purge_buffers(struct s_reader *reader)
471 int32_t result;
473 result = smartreader_usb_purge_rx_buffer(reader);
474 if(result < 0)
475 { return -1; }
477 result = smartreader_usb_purge_tx_buffer(reader);
478 if(result < 0)
479 { return -2; }
481 return 0;
484 static int smartreader_to_clkbits_AM(int baudrate, unsigned long *encoded_divisor)
487 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
488 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
489 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
490 int divisor, best_divisor, best_baud, best_baud_diff;
491 divisor = 24000000 / baudrate;
492 int i;
494 // Round down to supported fraction (AM only)
495 divisor -= am_adjust_dn[divisor & 7];
497 // Try this divisor and the one above it (because division rounds down)
498 best_divisor = 0;
499 best_baud = 0;
500 best_baud_diff = 0;
501 for (i = 0; i < 2; i++)
503 int try_divisor = divisor + i;
504 int baud_estimate;
505 int baud_diff;
507 // Round up to supported divisor value
508 if (try_divisor <= 8)
510 // Round up to minimum supported divisor
511 try_divisor = 8;
513 else if (divisor < 16)
515 // AM doesn't support divisors 9 through 15 inclusive
516 try_divisor = 16;
518 else
520 // Round up to supported fraction (AM only)
521 try_divisor += am_adjust_up[try_divisor & 7];
522 if (try_divisor > 0x1FFF8)
524 // Round down to maximum supported divisor value (for AM)
525 try_divisor = 0x1FFF8;
528 // Get estimated baud rate (to nearest integer)
529 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
530 // Get absolute difference from requested baud rate
531 if (baud_estimate < baudrate)
533 baud_diff = baudrate - baud_estimate;
535 else
537 baud_diff = baud_estimate - baudrate;
539 if (i == 0 || baud_diff < best_baud_diff)
541 // Closest to requested baud rate so far
542 best_divisor = try_divisor;
543 best_baud = baud_estimate;
544 best_baud_diff = baud_diff;
545 if (baud_diff == 0)
547 // Spot on! No point trying
548 break;
552 // Encode the best divisor value
553 *encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
554 // Deal with special cases for encoded value
555 if (*encoded_divisor == 1)
557 *encoded_divisor = 0; // 3000000 baud
559 else if (*encoded_divisor == 0x4001)
561 *encoded_divisor = 1; // 2000000 baud (BM only)
563 return best_baud;
566 /* ftdi_to_clkbits Convert a requested baudrate for a given system clock and predivisor
567 to encoded divisor and the achievable baudrate
568 Function is only used internally
569 \internal
571 See AN120
572 clk/1 -> 0
573 clk/1.5 -> 1
574 clk/2 -> 2
575 From /2, 0.125 steps may be taken.
576 The fractional part has frac_code encoding
578 value[13:0] of value is the divisor
579 index[9] mean 12 MHz Base(120 MHz/10) rate versus 3 MHz (48 MHz/16) else
581 H Type have all features above with
582 {index[8],value[15:14]} is the encoded subdivisor
584 FT232R, FT2232 and FT232BM have no option for 12 MHz and with
585 {index[0],value[15:14]} is the encoded subdivisor
587 AM Type chips have only four fractional subdivisors at value[15:14]
588 for subdivisors 0, 0.5, 0.25, 0.125
590 static int smartreader_to_clkbits(int baudrate, int clk, int clk_div, unsigned long *encoded_divisor)
592 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
593 int best_baud = 0;
594 int divisor, best_divisor;
595 if (baudrate >= clk/clk_div)
597 *encoded_divisor = 0;
598 best_baud = clk/clk_div;
600 else if (baudrate >= clk/(clk_div + clk_div/2))
602 *encoded_divisor = 1;
603 best_baud = clk/(clk_div + clk_div/2);
605 else if (baudrate >= clk/(2*clk_div))
607 *encoded_divisor = 2;
608 best_baud = clk/(2*clk_div);
610 else
612 /* We divide by 16 to have 3 fractional bits and one bit for rounding */
613 divisor = clk*16/clk_div / baudrate;
614 if (divisor & 1) /* Decide if to round up or down*/
615 best_divisor = divisor /2 +1;
616 else
617 best_divisor = divisor/2;
618 if(best_divisor > 0x20000)
619 best_divisor = 0x1ffff;
620 best_baud = clk*16/clk_div/best_divisor;
621 if (best_baud & 1) /* Decide if to round up or down*/
622 best_baud = best_baud /2 +1;
623 else
624 best_baud = best_baud /2;
625 *encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 0x7] << 14);
627 return best_baud;
630 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
631 Function is only used internally
632 \internal
634 static int smartreader_convert_baudrate(int baudrate, struct s_reader *reader, unsigned short *value, unsigned short *idx)
636 int best_baud;
637 unsigned long encoded_divisor;
638 struct sr_data *crdr_data = reader->crdr_data;
640 if (baudrate <= 0)
642 // return ERROR
643 return -1;
646 #define H_CLK 120000000
647 #define C_CLK 48000000
648 if ((crdr_data->type == TYPE_2232H) || (crdr_data->type == TYPE_4232H) || (crdr_data->type == TYPE_232H))
650 if(baudrate*10 > H_CLK /0x3fff)
652 /* On H Devices, use 12 000 000 Baudrate when possible
653 We have a 14 bit divisor, a 1 bit divisor switch (10 or 16)
654 three fractional bits and a 120 MHz clock
655 Assume AN_120 "Sub-integer divisors between 0 and 2 are not allowed" holds for
656 DIV/10 CLK too, so /1, /1.5 and /2 can be handled the same*/
657 best_baud = smartreader_to_clkbits(baudrate, H_CLK, 10, &encoded_divisor);
658 encoded_divisor |= 0x20000; /* switch on CLK/10*/
660 else
661 best_baud = smartreader_to_clkbits(baudrate, C_CLK, 16, &encoded_divisor);
663 else if ((crdr_data->type == TYPE_BM) || (crdr_data->type == TYPE_2232C) || (crdr_data->type == TYPE_R ))
665 best_baud = smartreader_to_clkbits(baudrate, C_CLK, 16, &encoded_divisor);
667 else
669 best_baud = smartreader_to_clkbits_AM(baudrate, &encoded_divisor);
671 // Split into "value" and "index" values
672 *value = (unsigned short)(encoded_divisor & 0xFFFF);
673 if (crdr_data->type == TYPE_2232H ||
674 crdr_data->type == TYPE_4232H || crdr_data->type == TYPE_232H)
676 *idx = (unsigned short)(encoded_divisor >> 8);
677 *idx &= 0xFF00;
678 *idx |= crdr_data->index;
680 else
681 *idx = (unsigned short)(encoded_divisor >> 16);
683 // Return the nearest baud rate
684 return best_baud;
688 Sets the chip baud rate
690 \param ftdi pointer to ftdi_context
691 \param baudrate baud rate to set
693 \retval 0: all fine
694 \retval -1: invalid baudrate
695 \retval -2: setting baudrate failed
696 \retval -3: USB device unavailable
698 int smartreader_set_baudrate(struct s_reader *reader, int baudrate)
700 struct sr_data *crdr_data = reader->crdr_data;
701 unsigned short value, idx;
702 int actual_baudrate;
704 if (crdr_data->usb_dev == NULL){
705 rdr_log(reader, "USB device unavailable");
706 return ERROR;
709 if (crdr_data->bitbang_enabled)
711 baudrate = baudrate*4;
714 actual_baudrate = smartreader_convert_baudrate(baudrate, reader, &value, &idx);
715 if (actual_baudrate <= 0) {
716 rdr_log(reader, "Silly baudrate <= 0.");
717 return (-1);
720 // Check within tolerance (about 5%)
721 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
722 || ((actual_baudrate < baudrate)
723 ? (actual_baudrate * 21 < baudrate * 20)
724 : (baudrate * 21 < actual_baudrate * 20))) {
725 rdr_log(reader, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
726 return (-1);
728 if (libusb_control_transfer(crdr_data->usb_dev_handle,
729 FTDI_DEVICE_OUT_REQTYPE,
730 SIO_SET_BAUDRATE_REQUEST,
731 value,
732 idx,
733 NULL,
735 crdr_data->usb_write_timeout) < 0) {
736 rdr_log(reader, "Setting new baudrate failed");
737 return (-2);
739 crdr_data->baudrate = baudrate;
740 // rdr_log(reader,"BAUDRATE IS NOW SET ON %u", crdr_data->baudrate);
741 // rdr_log(reader,"ACTUAL BAUDRATE = %u", actual_baudrate);
742 return 0;
745 static int32_t smartreader_setdtr_rts(struct s_reader *reader, int32_t dtr, int32_t rts)
747 struct sr_data *crdr_data = reader->crdr_data;
748 uint16_t usb_val;
751 if(dtr)
752 { usb_val = SIO_SET_DTR_HIGH; }
753 else
754 { usb_val = SIO_SET_DTR_LOW; }
756 if(rts)
757 { usb_val |= SIO_SET_RTS_HIGH; }
758 else
759 { usb_val |= SIO_SET_RTS_LOW; }
760 if(libusb_control_transfer(crdr_data->usb_dev_handle,
761 FTDI_DEVICE_OUT_REQTYPE,
762 SIO_SET_MODEM_CTRL_REQUEST,
763 usb_val,
764 crdr_data->index,
765 NULL,
767 crdr_data->usb_write_timeout) != 0)
769 rdr_log(reader, "set of rts/dtr failed");
770 return (-1);
772 return 0;
775 static int32_t smartreader_setflowctrl(struct s_reader *reader, int32_t flowctrl)
777 struct sr_data *crdr_data = reader->crdr_data;
778 if(libusb_control_transfer(crdr_data->usb_dev_handle,
779 FTDI_DEVICE_OUT_REQTYPE,
780 SIO_SET_FLOW_CTRL_REQUEST,
782 (flowctrl | crdr_data->index),
783 NULL,
785 crdr_data->usb_write_timeout) != 0)
787 rdr_log(reader, "set flow control failed");
788 return (-1);
790 return 0;
793 static int32_t smartreader_set_line_property2(struct s_reader *reader, enum smartreader_bits_type bits,
794 enum smartreader_stopbits_type sbit, enum smartreader_parity_type parity,
795 enum smartreader_break_type break_type)
797 struct sr_data *crdr_data = reader->crdr_data;
798 uint16_t value = bits;
800 switch(parity)
802 case NONE:
803 value |= (0x00 << 8);
804 break;
805 case ODD:
806 value |= (0x01 << 8);
807 break;
808 case EVEN:
809 value |= (0x02 << 8);
810 break;
811 case MARK:
812 value |= (0x03 << 8);
813 break;
814 case SPACE:
815 value |= (0x04 << 8);
816 break;
819 switch(sbit)
821 case STOP_BIT_1:
822 value |= (0x00 << 11);
823 break;
824 case STOP_BIT_15:
825 value |= (0x01 << 11);
826 break;
827 case STOP_BIT_2:
828 value |= (0x02 << 11);
829 break;
832 switch(break_type)
834 case BREAK_OFF:
835 value |= (0x00 << 14);
836 break;
837 case BREAK_ON:
838 value |= (0x01 << 14);
839 break;
841 if(libusb_control_transfer(crdr_data->usb_dev_handle,
842 FTDI_DEVICE_OUT_REQTYPE,
843 SIO_SET_DATA_REQUEST,
844 value,
845 crdr_data->index,
846 NULL,
848 crdr_data->usb_write_timeout) != 0)
850 rdr_log(reader, "Setting new line property failed");
851 return (-1);
853 return 0;
857 static int32_t smartreader_set_line_property(struct s_reader *reader, enum smartreader_bits_type bits,
858 enum smartreader_stopbits_type sbit, enum smartreader_parity_type parity)
860 return smartreader_set_line_property2(reader, bits, sbit, parity, BREAK_OFF);
865 static void smart_flush(struct s_reader *reader)
867 smartreader_usb_purge_buffers(reader);
869 struct sr_data *crdr_data = reader->crdr_data;
870 SAFE_MUTEX_LOCK(&crdr_data->g_read_mutex);
871 crdr_data->g_read_buffer_size = 0;
872 SAFE_MUTEX_UNLOCK(&crdr_data->g_read_mutex);
875 static int32_t smartreader_set_latency_timer(struct s_reader *reader, uint16_t latency)
877 struct sr_data *crdr_data = reader->crdr_data;
878 uint16_t usb_val;
880 if(latency < 1)
882 rdr_log(reader, "latency out of range. Only valid for 1-255");
883 return (-1);
886 usb_val = latency;
887 if(libusb_control_transfer(crdr_data->usb_dev_handle,
888 FTDI_DEVICE_OUT_REQTYPE,
889 SIO_SET_LATENCY_TIMER_REQUEST,
890 usb_val,
891 crdr_data->index,
892 NULL,
894 crdr_data->usb_write_timeout) != 0)
896 rdr_log(reader, "unable to set latency timer");
897 return (-2);
899 return 0;
902 #if defined(__CYGWIN__)
903 static WINAPI read_callback(struct libusb_transfer *transfer)
905 #else
906 static void read_callback(struct libusb_transfer *transfer)
908 #endif
909 struct s_reader *reader = (struct s_reader *)transfer->user_data;
910 struct sr_data *crdr_data = reader->crdr_data;
911 int32_t copy_size;
912 int32_t ret;
914 if(transfer->status == LIBUSB_TRANSFER_COMPLETED)
916 if(transfer->actual_length > 2) //FTDI always sends modem status bytes as first 2 chars with the 232BM
918 SAFE_MUTEX_LOCK(&crdr_data->g_read_mutex);
920 if(crdr_data->g_read_buffer_size == sizeof(crdr_data->g_read_buffer))
922 rdr_log(reader, "SR: buffer full");
923 //if out read buffer is full then delay
924 //slightly and go around again
925 ret = libusb_submit_transfer(transfer);
926 if(ret != 0)
927 { rdr_log(reader, "SR: submit async transfer failed with error %d", ret); }
928 SAFE_COND_SIGNAL(&crdr_data->g_read_cond);
929 SAFE_MUTEX_UNLOCK(&crdr_data->g_read_mutex);
930 return;
932 crdr_data->modem_status = transfer->buffer[0];
933 // rdr_log(reader, " Transfer Buf 0 = 0x%2x, Buf 1 = 0x%2x, Buf 2 = 0x%2x", transfer->buffer[0], transfer->buffer[1], transfer->buffer[2] );
935 copy_size = sizeof(crdr_data->g_read_buffer) - crdr_data->g_read_buffer_size > (uint32_t)transfer->actual_length - 2 ? (uint32_t)transfer->actual_length - 2 : sizeof(crdr_data->g_read_buffer) - crdr_data->g_read_buffer_size;
936 memcpy(crdr_data->g_read_buffer + crdr_data->g_read_buffer_size, transfer->buffer + 2, copy_size);
937 crdr_data->g_read_buffer_size += copy_size;
939 SAFE_COND_SIGNAL(&crdr_data->g_read_cond);
940 SAFE_MUTEX_UNLOCK(&crdr_data->g_read_mutex);
942 else
944 if(transfer->actual_length == 2)
946 SAFE_MUTEX_LOCK(&crdr_data->g_read_mutex);
947 crdr_data->modem_status = transfer->buffer[0];
948 SAFE_MUTEX_UNLOCK(&crdr_data->g_read_mutex);
952 ret = libusb_submit_transfer(transfer);
954 if(ret != 0)
955 { rdr_log(reader, "SR: submit async transfer failed with error %d", ret); }
958 else
960 if (!crdr_data->closing && init_count) {
961 rdr_log(reader, "SR: USB bulk read failed with error %d", transfer->status);
966 static int32_t smartreader_usb_open_dev(struct s_reader *reader)
968 struct sr_data *crdr_data = reader->crdr_data;
969 int32_t detach_errno = 0;
970 struct libusb_device_descriptor usbdesc;
971 int32_t ret;
973 #ifdef __WIN32__
974 int32_t config;
975 int32_t config_val = 1;
976 #endif
978 ret = libusb_open(crdr_data->usb_dev, &crdr_data->usb_dev_handle);
979 if(ret)
981 rdr_log(reader, "Coulnd't open smartreader device %03d:%03d", libusb_get_bus_number(crdr_data->usb_dev), libusb_get_device_address(crdr_data->usb_dev));
982 switch(ret)
984 case LIBUSB_ERROR_NO_MEM:
985 rdr_log(reader, "libusb_open error LIBUSB_ERROR_NO_MEM : memory allocation failure");
986 break;
987 case LIBUSB_ERROR_ACCESS:
988 rdr_log(reader, "libusb_open error LIBUSB_ERROR_ACCESS : the user has insufficient permissions");
989 break;
990 case LIBUSB_ERROR_NO_DEVICE:
991 rdr_log(reader, "libusb_open error LIBUSB_ERROR_NO_DEVICE : the device has been disconnected");
992 break;
993 default:
994 rdr_log(reader, "libusb_open unknown error : %d", ret);
995 break;
997 return (-4);
1000 #if defined(__linux__)
1001 // Try to detach ftdi_sio kernel module.
1002 // Returns ENODATA if driver is not loaded.
1004 // The return code is kept in a separate variable and only parsed
1005 // if usb_set_configuration() or usb_claim_interface() fails as the
1006 // detach operation might be denied and everything still works fine.
1007 // Likely scenario is a static smartreader_sio kernel module.
1008 if(libusb_detach_kernel_driver(crdr_data->usb_dev_handle, crdr_data->interface) != 0 && errno != ENODATA)
1010 smartreader_usb_close_internal(reader);
1011 rdr_log(reader, "Couldn't detach interface from kernel. Please unload the FTDI drivers");
1012 return (LIBUSB_ERROR_NOT_SUPPORTED);
1014 #endif
1015 ret = libusb_get_device_descriptor(crdr_data->usb_dev, &usbdesc);
1016 if(ret != 0) {
1017 rdr_log_dbg(reader, D_IFD, "libusb_get_device_descriptor failed");
1018 } else {
1019 rdr_log_dbg(reader, D_IFD, "libusb_get_device_descriptor ok");
1022 #ifdef __WIN32__
1023 // set configuration (needed especially for windows)
1024 // tolerate EBUSY: one device with one configuration, but two interfaces
1025 // and libftdi sessions to both interfaces (e.g. FT2232)
1027 if(usbdesc.bNumConfigurations > 0)
1029 ret = libusb_get_configuration(crdr_data->usb_dev_handle, &config);
1031 // libusb-win32 on Windows 64 can return a null pointer for a valid device
1032 if(libusb_set_configuration(crdr_data->usb_dev_handle, config) && errno != EBUSY)
1034 smartreader_usb_close_internal(reader);
1035 if(detach_errno == EPERM)
1037 rdr_log(reader, "inappropriate permissions on device!");
1038 return (-8);
1039 } else {
1040 rdr_log(reader, "unable to set usb configuration. Make sure smartreader_sio is unloaded!");
1041 return (-3);
1043 } else {
1044 rdr_log_dbg(rdr, D_IFD, "libusb_set_configuration failed");
1047 #endif
1049 ret = libusb_claim_interface(crdr_data->usb_dev_handle, crdr_data->interface) ;
1051 if(ret != 0)
1053 smartreader_usb_close_internal(reader);
1054 if(detach_errno == EPERM)
1056 rdr_log(reader, "inappropriate permissions on device!");
1057 return (-8);
1058 } else {
1059 rdr_log(reader, "unable to claim usb device. Make sure smartreader_sio is unloaded!");
1060 return (-5);
1063 else {
1064 rdr_log_dbg(reader, D_IFD, "smartreader_usb_close_internal OK");
1067 if(smartreader_usb_reset(reader) != 0)
1069 libusb_release_interface(crdr_data->usb_dev_handle, crdr_data->interface);
1070 smartreader_usb_close_internal(reader);
1071 rdr_log(reader, "smartreader_usb_reset failed");
1072 return (-6);
1075 // Try to guess chip type
1076 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
1077 if(usbdesc.bcdDevice == 0x400 || (usbdesc.bcdDevice == 0x200 && usbdesc.iSerialNumber == 0))
1078 { crdr_data->type = TYPE_BM; }
1079 else if(usbdesc.bcdDevice == 0x200)
1080 { crdr_data->type = TYPE_AM; }
1081 else if(usbdesc.bcdDevice == 0x500)
1083 if(usbdesc.idProduct == 0x6011)
1085 crdr_data->type = TYPE_4232H;
1086 } else {
1087 crdr_data->type = TYPE_2232C;
1090 else if(usbdesc.bcdDevice == 0x600)
1091 { crdr_data->type = TYPE_R; }
1092 else if(usbdesc.bcdDevice == 0x700)
1093 { crdr_data->type = TYPE_2232H; }
1094 else if(usbdesc.bcdDevice == 0x800)
1095 { crdr_data->type = TYPE_4232H; }
1097 // Determine maximum packet size
1098 crdr_data->max_packet_size = smartreader_determine_max_packet_size(reader);
1099 rdr_log_dbg(reader, D_IFD, "FTDI CHIP %s", type_str[crdr_data->type]);
1100 rdr_log_dbg(reader, D_IFD, "max packet size is %u", crdr_data->max_packet_size);
1102 if(smartreader_set_baudrate(reader, 9600) != 0)
1104 libusb_release_interface(crdr_data->usb_dev_handle, crdr_data->interface);
1105 smartreader_usb_close_internal(reader);
1106 rdr_log(reader, "set baudrate failed");
1107 return (-7);
1110 return (0);
1113 static void EnableSmartReader(struct s_reader *reader, uint32_t baud_temp2, int32_t clock_val, uint16_t Fi, unsigned char Di, unsigned char Ni, unsigned char T, unsigned char inv, int32_t parity)
1115 struct sr_data *crdr_data = reader->crdr_data;
1116 unsigned char FiDi[4];
1117 uint16_t freqk;
1118 unsigned char Freq[3];
1119 unsigned char N[2];
1120 unsigned char Prot[2];
1121 unsigned char Invert[2];
1122 unsigned char temp_T;
1124 smartreader_set_baudrate(reader, baud_temp2);
1125 smartreader_setflowctrl(reader, 0);
1126 if (crdr_data->rdrtype >= 2) cs_sleepms(150); // for changing a line setting the V2 and Triple need a delay
1127 smartreader_set_line_property(reader, (enum smartreader_bits_type) 5, STOP_BIT_2, NONE);
1129 // command 1, set F and D parameter
1130 if(!crdr_data->irdeto)
1132 rdr_log_dbg(reader, D_DEVICE, "SR: sending F=%04X (%d) to smartreader", Fi, Fi);
1133 rdr_log_dbg(reader, D_DEVICE, "SR: sending D=%02X (%d) to smartreader", Di, Di);
1134 FiDi[0] = 0x01;
1135 FiDi[1] = HIBYTE(Fi);
1136 FiDi[2] = LOBYTE(Fi);
1137 FiDi[3] = Di;
1138 smart_write(reader, FiDi, sizeof(FiDi));
1140 else
1142 rdr_log_dbg(reader, D_IFD, "Not setting F and D as we're in Irdeto mode");
1145 // command 2, set the frequency in KHz
1146 // 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
1147 freqk = clock_val * 10; //clock with type int32_t couldnt hold freq in Hz on all platforms, so I reverted to 10khz units (like mhz) - dingo
1148 rdr_log_dbg(reader, D_DEVICE, "SR: sending Freq=%04X (%d) to smartreader", freqk, freqk);
1149 Freq[0] = 0x02;
1150 Freq[1] = HIBYTE(freqk);
1151 Freq[2] = LOBYTE(freqk);
1152 smart_write(reader, Freq, sizeof(Freq));
1154 // command 3, set paramter N
1155 rdr_log_dbg(reader, D_DEVICE, "SR: sending N=%02X (%d) to smartreader", Ni, Ni);
1156 N[0] = 0x03;
1157 N[1] = Ni;
1158 smart_write(reader, N, sizeof(N));
1160 // command 4 , set parameter T
1161 temp_T = T;
1162 if(T == 2) // 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
1163 //if(crdr_data->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
1165 T = 1;
1166 crdr_data->T = 1;
1167 temp_T = 1;
1169 else if(T == 1)
1170 { T = 0; } // T=1 protocol is handled by oscam
1172 rdr_log_dbg(reader, D_DEVICE, "SR: sending T=%02X (%d) to smartreader", T, T);
1173 Prot[0] = 0x04;
1174 Prot[1] = T;
1175 smart_write(reader, Prot, sizeof(Prot));
1177 // command 5, set invert y/n
1178 rdr_log_dbg(reader, D_DEVICE, "SR: sending inv=%02X to smartreader", inv);
1179 Invert[0] = 0x05;
1180 Invert[1] = inv;
1181 smart_write(reader, Invert, sizeof(Invert));
1183 cs_sleepms(250); // this delay needed for Triple and v2
1184 smartreader_set_line_property2(reader, BITS_8, STOP_BIT_2, parity, BREAK_ON);
1185 // send break for 350ms, also comes from JoePub debugging.break
1186 cs_sleepms(350);
1189 if(temp_T == 1)
1190 { smartreader_set_line_property2(reader, BITS_8, STOP_BIT_1, parity, BREAK_OFF); }
1191 else
1192 { smartreader_set_line_property2(reader, BITS_8, STOP_BIT_2, parity, BREAK_OFF); }
1194 cs_sleepus(800);
1195 smart_flush(reader);
1196 cs_sleepus(800);
1197 crdr_data->detectstart = 1;
1202 static void *ReaderThread(void *p)
1204 struct s_reader *reader;
1205 int32_t ret, idx;
1207 reader = (struct s_reader *)p;
1208 struct sr_data *crdr_data = reader->crdr_data;
1209 crdr_data->running = 1;
1211 set_thread_name(__func__);
1213 for(idx = 0; idx < NUM_TXFERS; idx++)
1216 crdr_data->usbt[idx] = libusb_alloc_transfer(0);
1217 libusb_fill_bulk_transfer(crdr_data->usbt[idx],
1218 crdr_data->usb_dev_handle,
1219 crdr_data->out_ep,
1220 crdr_data->usb_buffers[idx],
1222 (void *)(&read_callback),
1223 reader,
1226 ret = libusb_submit_transfer(crdr_data->usbt[idx]);
1227 if(ret != 0)
1229 rdr_log_dbg(reader, D_IFD, "libusb_submit_transfer ok");
1230 } else {
1231 rdr_log_dbg(reader, D_IFD, "libusb_submit_transfer failed");
1235 while(crdr_data->running)
1237 ret = libusb_handle_events(NULL);
1238 if(ret != 0)
1239 { rdr_log(reader, "libusb_handle_events returned with %d", ret); }
1241 SAFE_MUTEX_LOCK(&crdr_data->g_usb_mutex);
1242 if(!crdr_data->poll)
1244 struct timespec timeout;
1245 add_ms_to_timespec(&timeout, 2000);
1246 SAFE_COND_TIMEDWAIT(&crdr_data->g_usb_cond, &crdr_data->g_usb_mutex, &timeout);
1248 SAFE_MUTEX_UNLOCK(&crdr_data->g_usb_mutex);
1251 pthread_exit(NULL);
1254 static void smart_fastpoll(struct s_reader *reader, int32_t on)
1256 struct sr_data *crdr_data = reader->crdr_data;
1257 SAFE_MUTEX_LOCK(&crdr_data->g_usb_mutex);
1258 //printf("poll stat: %d\n", on);
1259 crdr_data->poll = on;
1260 SAFE_COND_SIGNAL(&crdr_data->g_usb_cond);
1261 SAFE_MUTEX_UNLOCK(&crdr_data->g_usb_mutex);
1264 static int32_t SR_Init(struct s_reader *reader)
1266 uint8_t i = 0;
1267 while(reader->handle_nr > 0 && i < 10) // Restarting the reader while it was not closed does cause segfault.
1269 i++;
1270 rdr_log(reader," Wait on close before restart second %u", i);
1271 cs_sleepms(1000);
1274 int32_t ret;
1275 char device[cs_strlen(reader->device) + 1];
1276 char *rdrtype, *busname, *dev, *search = ":", *saveptr1 = NULL;
1277 memcpy(device, reader->device, cs_strlen(reader->device) + 1);
1278 // split the device name from the reader conf into devname and busname. rdrtype is optional
1279 rdrtype = strtok_r(device, ";", &saveptr1);
1280 busname = strtok_r(NULL, ":", &saveptr1);
1281 dev = strtok_r(NULL, ":", &saveptr1);
1282 if(!busname)
1284 rdrtype = "SR";
1285 memcpy(device, reader->device, cs_strlen(reader->device) + 1);
1286 busname = strtok_r(device, ":", &saveptr1);
1287 dev = strtok_r(NULL, search, &saveptr1);
1290 if(!busname || !dev)
1292 rdr_log(reader, "Wrong device format (%s), it should be Device=bus:dev", reader->device);
1293 return ERROR;
1296 if(!reader->crdr_data && !cs_malloc(&reader->crdr_data, sizeof(struct sr_data)))
1297 { return ERROR; }
1298 struct sr_data *crdr_data = reader->crdr_data;
1299 crdr_data->detectstart = 0;
1300 crdr_data->tripledelay = 0;
1301 if (!strcasecmp(rdrtype, "SR")) {
1302 crdr_data->rdrtype = SR;
1304 if (!strcasecmp(rdrtype, "Infinity")) {
1305 crdr_data->rdrtype = Infinity;
1307 if (!strcasecmp(rdrtype, "SRv2")) {
1308 crdr_data->tripledelay = 0;
1309 crdr_data->rdrtype = SRv2;
1311 if (!strcasecmp(rdrtype, "TripleP1")) {
1312 crdr_data->tripledelay = 0;
1313 crdr_data->rdrtype = TripleP1;
1315 if (!strcasecmp(rdrtype, "TripleP2")) {
1316 crdr_data->tripledelay = 100;
1317 crdr_data->rdrtype = TripleP2;
1319 if (!strcasecmp(rdrtype, "TripleP3")) {
1320 crdr_data->tripledelay = 150;
1321 crdr_data->rdrtype = TripleP3;
1324 rdr_log_dbg(reader, D_DEVICE, "SR: Looking for device %s on bus %s", dev, busname);
1325 cs_writelock(__func__, &sr_lock);
1326 smartreader_init(reader);
1328 if(!init_count)
1330 ret = libusb_init(NULL);
1331 if(ret < 0)
1333 cs_writeunlock(__func__, &sr_lock);
1334 rdr_log(reader, "Libusb init error : %d", ret);
1335 return ret;
1338 init_count++;
1339 current_count++;
1341 rdr_log_dbg(reader, D_IFD, "Using 0x%02X/0x%02X as endpoint for smartreader hardware detection", crdr_data->in_ep, crdr_data->out_ep);
1342 if (crdr_data->tripledelay > 0) {
1343 cs_writeunlock(__func__, &sr_lock);
1344 cs_sleepms(crdr_data->tripledelay);
1345 cs_writelock(__func__, &sr_lock);
1347 crdr_data->usb_dev = find_smartreader(reader, busname, dev, crdr_data->in_ep, crdr_data->out_ep);
1348 if(!crdr_data->usb_dev)
1350 --init_count;
1351 --current_count;
1352 if(!init_count)
1353 { libusb_exit(NULL); }
1354 cs_writeunlock(__func__, &sr_lock);
1355 return ERROR;
1358 rdr_log_dbg(reader, D_DEVICE, "SR: Opening smartreader device %s on bus %s endpoint in 0x%02X out 0x%02X", dev, busname, crdr_data->in_ep, crdr_data->out_ep);
1360 if((ret = smartreader_usb_open_dev(reader)))
1362 --init_count;
1363 --current_count;
1364 if(!init_count)
1365 { libusb_exit(NULL); }
1366 cs_writeunlock(__func__, &sr_lock);
1367 rdr_log(reader, "Unable to open smartreader device %s in bus %s endpoint in 0x%02X out 0x%02X (ret=%d)\n", dev, busname, crdr_data->in_ep, crdr_data->out_ep, ret);
1368 return ERROR;
1371 if (crdr_data->rdrtype >= 2) {
1372 //Set the FTDI latency timer to 16 ms is ftdi default latency.
1373 ret = smartreader_set_latency_timer(reader, 16);
1374 rdr_log_dbg(reader, D_DEVICE, "SR: Setting smartreader latency timer to %d ms", ret);
1375 } else {
1376 //Set the FTDI latency timer to 1 ms .
1377 ret = smartreader_set_latency_timer(reader, 1);
1378 rdr_log_dbg(reader, D_DEVICE, "SR: Setting smartreader latency timer to %d ms", ret);
1381 //Set databits to 8o2
1382 ret = smartreader_set_line_property(reader, BITS_8, STOP_BIT_2, ODD);
1383 if(ret != 0)
1385 rdr_log_dbg(reader, D_IFD, "smartreader_set_line_property ok");
1386 } else {
1387 rdr_log_dbg(reader, D_IFD, "smartreader_set_line_property failed");
1390 //Set the DTR LOW and RTS LOW
1391 ret = smartreader_setdtr_rts(reader, 0, 0);
1392 if(ret != 0)
1394 rdr_log_dbg(reader, D_IFD, "smartreader_setdtr_rts ok");
1395 } else {
1396 rdr_log_dbg(reader, D_IFD, "smartreader_setdtr_rts failed");
1399 //Disable flow control
1400 ret = smartreader_setflowctrl(reader, 0);
1401 if(ret != 0)
1403 rdr_log_dbg(reader, D_IFD, "smartreader_setflowctrl ok");
1404 } else {
1405 rdr_log_dbg(reader, D_IFD, "smartreader_setflowctrl failed");
1408 // start the reading thread
1409 crdr_data->g_read_buffer_size = 0;
1410 crdr_data->modem_status = 0 ;
1411 cs_pthread_cond_init(__func__, &crdr_data->g_read_mutex, &crdr_data->g_read_cond);
1412 cs_pthread_cond_init(__func__, &crdr_data->g_usb_mutex, &crdr_data->g_usb_cond);
1414 cs_writeunlock(__func__, &sr_lock);
1415 ret = start_thread("smartreader", ReaderThread, (void *)(reader), &crdr_data->rt, 0, 0);
1416 if(ret)
1418 --init_count;
1419 --current_count;
1420 return ERROR;
1423 reader->handle_nr = (long)crdr_data->usb_dev_handle + 1;
1425 return OK;
1428 static int32_t SR_Reset(struct s_reader *reader, ATR *atr)
1430 struct sr_data *crdr_data = reader->crdr_data;
1431 unsigned char data[ATR_MAX_SIZE];
1432 int32_t ret;
1433 int32_t atr_ok;
1434 uint32_t baud_temp2;
1435 int32_t i;
1436 int32_t parity[4] = {EVEN, ODD, NONE, EVEN}; // the last EVEN is to try with different F, D values for irdeto card.
1437 static const char *const parity_str[5] = {"NONE", "ODD", "EVEN", "MARK", "SPACE"};
1439 // seems to be ok after all
1440 if (reader->cardmhz == reader->mhz && reader->cardmhz > 369)
1441 crdr_data->fs = reader->cardmhz * 10000; else
1442 crdr_data->fs = 3690000;
1444 rdr_log_dbg(reader, D_IFD, " init card at %u mhz", crdr_data->fs / 10000);
1446 smart_fastpoll(reader, 1);
1447 // set smartreader+ default values
1448 crdr_data->F = 372;
1449 crdr_data->D = 1;
1450 crdr_data->N = 0;
1451 crdr_data->T = 1;
1452 crdr_data->inv = 0;
1453 baud_temp2 = (double)(crdr_data->D * crdr_data->fs / (double)crdr_data->F);
1454 // rdr_log(reader,"CARD INIT BAUDRATE = %u", baud_temp2);
1456 for(i = 0 ; i < 4 ; i++)
1458 crdr_data->irdeto = 0;
1459 atr_ok = ERROR;
1460 memset(data, 0, sizeof(data));
1461 rdr_log_dbg(reader, D_IFD, "SR: Trying with parity %s", parity_str[parity[i]]);
1463 // special irdeto case
1464 if(i == 3)
1466 rdr_log_dbg(reader, D_DEVICE, "SR: Trying irdeto");
1467 crdr_data->F = 618; // why 618 needs to be used instead off 558 ? but magic it is
1468 crdr_data->D = 1;
1469 crdr_data->T = 2; // will be set to T=1 in EnableSmartReader
1470 crdr_data->fs = 6000000;
1471 baud_temp2 = (double)(crdr_data->D * crdr_data->fs / (double)crdr_data->F);
1474 smart_flush(reader);
1475 EnableSmartReader(reader, baud_temp2, crdr_data->fs / 10000, crdr_data->F, (unsigned char)crdr_data->D, crdr_data->N, crdr_data->T, crdr_data->inv, parity[i]);
1477 //Reset smartcard
1479 //Set the DTR HIGH and RTS HIGH
1480 smartreader_setdtr_rts(reader, 1, 1);
1482 // A card with an active low reset is reset by maintaining RST in state L for at least 40 000 clock cycles
1483 // so if we have a base freq of 3.5712MHz : 40000/3690000 = .0112007168458781 seconds, aka 11ms
1484 // so if we have a base freq of 6.00MHz : 40000/6000000 = .0066666666666666 seconds, aka 6ms
1485 cs_sleepms(25);
1487 //Set the DTR HIGH and RTS LOW
1489 smartreader_setdtr_rts(reader, 1, 0);
1492 //Read the ATR
1493 ret = smart_read(reader, data, ATR_MAX_SIZE, (800)); // timeouts are in ms by smartreader
1494 rdr_log_dbg(reader, D_DEVICE, "SR: get ATR ret = %d" , ret);
1495 if(ret)
1496 { rdr_log_dump_dbg(reader, D_DEVICE, data, ATR_MAX_SIZE * 2, "SR:"); }
1498 // this is to make sure we don't think this 03 FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 is a valid ATR.
1499 if((data[0] != 0x3B && data[0] != 0x03 && data[0] != 0x3F) || (data[1] == 0xFF && data[2] == 0x00))
1501 crdr_data->irdeto = 0;
1502 continue; // this is not a valid ATR.
1505 if(data[0] == 0x03)
1507 rdr_log_dbg(reader, D_DEVICE, "SR: Inverse convention detected, setting smartreader inv to 1");
1509 crdr_data->inv = 1;
1510 EnableSmartReader(reader, baud_temp2, crdr_data->fs / 10000, crdr_data->F, (unsigned char)crdr_data->D, crdr_data->N, crdr_data->T, crdr_data->inv, parity[i]);
1512 // parse atr
1513 if(ATR_InitFromArray(atr, data, ret) != ERROR)
1515 rdr_log_dbg(reader, D_DEVICE, "SR: ATR parsing OK");
1516 atr_ok = OK;
1517 if(i == 3)
1519 crdr_data->irdeto = 1;
1520 rdr_log_dbg(reader, D_IFD, "SR: Locking F and D for Irdeto mode irdeto = %u", crdr_data->irdeto = 1);
1524 if(atr_ok == OK) {break;}
1526 smart_fastpoll(reader, 0);
1528 return atr_ok;
1531 static int32_t SR_Transmit(struct s_reader *reader, unsigned char *buffer, uint32_t size, uint32_t UNUSED(expectedlen), uint32_t delay, uint32_t timeout) // delay and timeout not used (yet)!
1533 (void) delay; // delay not used (yet)!
1534 (void) timeout; // timeout not used (yet)!
1535 uint32_t ret;
1537 smart_fastpoll(reader, 1);
1538 ret = smart_write(reader, buffer, size);
1539 smart_fastpoll(reader, 0);
1540 if(ret != size)
1541 { return ERROR; }
1543 return OK;
1546 static int32_t SR_GetStatus(struct s_reader *reader, int32_t *in)
1548 struct sr_data *crdr_data = reader->crdr_data;
1549 if (crdr_data->rdrtype >= 3)
1551 char usb_val[2];
1552 uint32_t state2;
1554 if (crdr_data->usb_dev == NULL)
1556 rdr_log(reader,"usb device unavailable");
1557 return ERROR;
1559 if (crdr_data->detectstart == 0)
1561 *in = 1;
1562 return OK;
1564 else
1566 if (((crdr_data->detectstart == 1) && (reader->card_status != 1)) && ((crdr_data->detectstart == 1) && (reader->card_status != 0)))
1568 cs_writelock(__func__, &sr_lock);
1569 if (libusb_control_transfer(crdr_data->usb_dev_handle,
1570 FTDI_DEVICE_IN_REQTYPE,
1571 SIO_POLL_MODEM_STATUS_REQUEST,
1572 2, crdr_data->index,
1573 (unsigned char *)usb_val,
1574 2, crdr_data->usb_read_timeout) != 1)
1576 rdr_log(reader, "getting modem status failed ");
1577 cs_writeunlock(__func__, &sr_lock);
1578 return ERROR;
1580 cs_writeunlock(__func__, &sr_lock);
1581 state2 = (usb_val[0] & 0xFF);
1582 rdr_log_dbg(reader, D_IFD, "the status of card in or out %u ( 64 means card IN)", state2);
1583 if (state2 == 64)
1585 *in = 1; //Card is activated
1587 else
1589 *in = 0; //NOCARD reader will be set to off
1591 return OK;
1593 else
1595 *in = 1;
1596 rdr_log(reader,"CARD STILL IN AKTIVATION PROCESS NO DETECTION");
1597 return OK;
1601 else
1603 int32_t state;
1605 smart_fastpoll(reader, 1);
1606 SAFE_MUTEX_LOCK(&crdr_data->g_read_mutex);
1607 state = (crdr_data->modem_status & 0x80) == 0x80 ? 0 : 2;
1608 SAFE_MUTEX_UNLOCK(&crdr_data->g_read_mutex);
1609 smart_fastpoll(reader, 0);
1610 rdr_log_dbg(reader, D_IFD, "the status of card in or out old procedure for v1 %u ", state);
1611 //state = 0 no card, 1 = not ready, 2 = ready
1612 if(state)
1613 { *in = 1; } //CARD, even if not ready report card is in, or it will never get activated
1614 else
1615 { *in = 0; } //NOCARD
1617 return OK;
1621 static int32_t SR_Receive(struct s_reader *reader, unsigned char *buffer, uint32_t size, uint32_t delay, uint32_t timeout)
1623 (void) delay; // delay not used (yet)!
1624 uint32_t ret;
1625 double timeout2;
1626 smart_fastpoll(reader, 1);
1627 if(reader->smart_type >= 2)
1629 timeout2 = ((double)timeout/1000) * 1.09;
1630 // rdr_log(reader," TEMPO test read timeout adapted for triple to %4.2f", timeout2);
1632 else
1634 timeout2 = (double)timeout/1000;
1636 // Limit the max timeout to 14 seconds to avoid a device read timeout.
1637 timeout2 = MIN(timeout2, 14000); // convert timeout to ms precize
1638 if (timeout2 < (double)timeout/1000)
1640 rdr_log_dbg(reader, D_IFD, "the max timeout has been limited to 14000 ms the calculated is %4.2f", (double)timeout/1000);
1642 ret = smart_read(reader, buffer, size, (double)timeout2);
1643 smart_fastpoll(reader, 0);
1644 if(ret != size)
1645 { return ERROR; }
1647 return OK;
1650 int32_t SR_WriteSettings(struct s_reader *reader, uint16_t F, unsigned char D, uint32_t N, unsigned char T, uint16_t convention)
1652 // 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
1653 struct sr_data *crdr_data = reader->crdr_data;
1654 crdr_data->inv = convention;//FIXME this one is set by icc_async and local smartreader reset routine
1655 static const char *const parity_str[5] = {"NONE", "ODD", "EVEN", "MARK", "SPACE"};
1656 rdr_log_dbg(reader, D_IFD, "autospeed = %u", reader->autospeed);
1657 rdr_log(reader, "Effective reader settings mhz =%u F= %u D= %u N=%u T=%u inv=%u parity=%s", reader->mhz, F, D, N, T, crdr_data->inv, parity_str[crdr_data->parity]);
1658 smart_fastpoll(reader, 1);
1659 uint32_t baud_temp2 = 3000000; //set to max device speed compatible with usb 1.1 card sets the baudrate.
1660 smart_flush(reader);
1661 EnableSmartReader(reader, baud_temp2, reader->mhz, F, D, N, T, crdr_data->inv, crdr_data->parity);
1662 smart_fastpoll(reader, 0);
1664 return OK;
1667 static int32_t SR_SetParity(struct s_reader *reader, uint8_t parity)
1669 struct sr_data *crdr_data = reader->crdr_data;
1670 int32_t ret;
1672 static const char *const parity_str[5] = {"NONE", "ODD", "EVEN", "MARK", "SPACE"};
1673 rdr_log_dbg(reader, D_DEVICE, "SR: Setting parity to %s", parity_str[parity]);
1675 crdr_data->parity = parity;
1676 smart_fastpoll(reader, 1);
1677 ret = smartreader_set_line_property(reader, (enum smartreader_bits_type) 8, STOP_BIT_2, parity);
1678 smart_fastpoll(reader, 0);
1679 if(ret)
1680 { return ERROR; }
1682 return OK;
1685 static int32_t SR_Close(struct s_reader *reader)
1687 struct sr_data *crdr_data = reader->crdr_data;
1688 if(!crdr_data) { return OK; }
1689 crdr_data->running = 0;
1690 if(crdr_data->usb_dev_handle)
1692 crdr_data->closing = 1;
1693 if (init_count >= 2)
1695 init_count--;
1696 smart_fastpoll(reader, 1);
1697 cs_writeunlock(__func__, &sr_lock);
1698 SAFE_THREAD_JOIN(crdr_data->rt, NULL);
1699 smart_fastpoll(reader, 0);
1701 else
1703 init_count--;
1705 reader->seca_nagra_card = 0;
1706 cs_writelock(__func__, &sr_lock);
1707 libusb_release_interface(crdr_data->usb_dev_handle, crdr_data->interface);
1708 #if defined(__linux__)
1709 // libusb_attach_kernel_driver(crdr_data->usb_dev_handle, crdr_data->interface); // attaching kernel drive
1710 #endif
1711 libusb_close(crdr_data->usb_dev_handle);
1712 crdr_data->usb_dev_handle = NULL;
1713 cs_writeunlock(__func__, &sr_lock);
1714 crdr_data->closing = 0;
1715 NULLFREE(reader->crdr_data); //clearing allocated mem
1716 NULLFREE(reader->csystem_data); //clearing allocated mem
1717 current_count--; // this reader may be restarted now
1718 if(!current_count)
1720 libusb_exit(NULL);
1724 init_lock = 0;
1725 reader->handle_nr = 0;
1726 rdr_log(reader,"SR: smartreader closed");
1728 return OK;
1731 /*static int32_t SR_FastReset(struct s_reader *reader, int32_t delay)
1733 unsigned char data[ATR_MAX_SIZE];
1735 smart_fastpoll(reader, 1);
1736 //Set the DTR HIGH and RTS HIGH
1737 smartreader_setdtr_rts(reader, 1, 1);
1738 // A card with an active low reset is reset by maintaining RST in state L for at least 40 000 clock cycles
1739 // so if we have a base freq of 3.5712MHz : 40000/3690000 = .0112007168458781 seconds, aka 11ms
1740 // so if we have a base freq of 6.00MHz : 40000/6000000 = .0066666666666666 seconds, aka 6ms
1741 cs_sleepms(delay);
1743 //Set the DTR HIGH and RTS LOW
1744 smartreader_setdtr_rts(reader, 1, 0);
1746 //Read the ATR
1747 smart_read(reader,data, ATR_MAX_SIZE,1000);
1748 smart_fastpoll(reader, 0);
1749 return 0;
1750 } */
1752 static int32_t SR_FastReset_With_ATR(struct s_reader *reader, ATR *atr)
1754 unsigned char data[ATR_MAX_SIZE];
1755 int32_t ret = 0;
1756 int32_t atr_ok = ERROR;
1757 int8_t atr_len = 0;
1758 if(reader->seca_nagra_card == 1)
1760 atr_len = reader->card_atr_length; // this is a special case the data buffer has only the atr length.
1762 else
1764 atr_len = reader->card_atr_length + 2; // data buffer has atr length + 2 bytes
1767 smart_fastpoll(reader, 1);
1768 //Set the DTR HIGH and RTS HIGH
1769 smartreader_setdtr_rts(reader, 1, 1);
1770 // A card with an active low reset is reset by maintaining RST in state L for at least 40 000 clock cycles
1771 // so if we have a base freq of 3.5712MHz : 40000/3690000 = .0112007168458781 seconds, aka 11ms
1772 // so if we have a base freq of 6.00MHz : 40000/6000000 = .0066666666666666 seconds, aka 6ms
1773 cs_sleepms(25);
1775 //Set the DTR HIGH and RTS LOW
1776 smartreader_setdtr_rts(reader, 1, 0);
1778 //Read the ATR
1779 ret = smart_read(reader, data, atr_len , (800)); // timeouts are in ms by smartreader.
1781 // parse atr
1782 if (ATR_InitFromArray(atr, data, ret) != ERROR)
1784 rdr_log_dbg(reader, D_DEVICE, "SR: ATR parsing OK");
1785 atr_ok = OK;
1788 smart_fastpoll(reader, 0);
1789 return atr_ok;
1792 int32_t SR_Activate(struct s_reader *reader, struct s_ATR *atr)
1794 if(!reader->ins7e11_fast_reset)
1796 call(SR_Reset(reader, atr));
1798 else
1800 call(SR_FastReset_With_ATR(reader, atr));
1802 return OK;
1805 int32_t sr_write_settings(struct s_reader *reader, struct s_cardreader_settings *s)
1807 SR_WriteSettings(reader, s->Fi, s->D, s->EGT, (unsigned char)reader->protocol_type, reader->convention);
1808 return OK;
1811 static int32_t sr_init_locks(struct s_reader *UNUSED(reader))
1813 if (!init_lock) {
1814 init_lock = 1;
1815 cs_lock_create(__func__, &sr_lock, "sr_lock", 5000);
1818 return OK;
1821 const struct s_cardreader cardreader_smartreader =
1823 .desc = "smartreader",
1824 .typ = R_SMART,
1825 .reader_init = SR_Init,
1826 .get_status = SR_GetStatus,
1827 .set_parity = SR_SetParity,
1828 .activate = SR_Activate,
1829 .transmit = SR_Transmit,
1830 .receive = SR_Receive,
1831 .close = SR_Close,
1832 .write_settings = sr_write_settings,
1833 .lock_init = sr_init_locks,
1836 #endif