• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /** ----------------------------------------------------------------------
2  *
3  * Copyright (C) 2013 ST Microelectronics S.A.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  *
18  ----------------------------------------------------------------------*/
19 #define _GNU_SOURCE
20 #include <assert.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <linux/input.h> /* not required for all builds */
25 #include <poll.h>
26 #include <pthread.h>
27 #include <stdint.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/ioctl.h>
32 #include <unistd.h>
33 
34 #include "android_logmsg.h"
35 #include "halcore.h"
36 #include "halcore_private.h"
37 
38 #define ST21NFC_MAGIC 0xEA
39 
40 #define ST21NFC_GET_WAKEUP _IOR(ST21NFC_MAGIC, 0x01, unsigned int)
41 #define ST21NFC_PULSE_RESET _IOR(ST21NFC_MAGIC, 0x02, unsigned int)
42 #define ST21NFC_SET_POLARITY_RISING _IOR(ST21NFC_MAGIC, 0x03, unsigned int)
43 #define ST21NFC_SET_POLARITY_FALLING _IOR(ST21NFC_MAGIC, 0x04, unsigned int)
44 #define ST21NFC_SET_POLARITY_HIGH _IOR(ST21NFC_MAGIC, 0x05, unsigned int)
45 #define ST21NFC_SET_POLARITY_LOW _IOR(ST21NFC_MAGIC, 0x06, unsigned int)
46 
47 #define LINUX_DBGBUFFER_SIZE 300
48 
49 static int fidI2c = 0;
50 static int cmdPipe[2] = {0, 0};
51 
52 static struct pollfd event_table[2];
53 static pthread_t threadHandle = (pthread_t)NULL;
54 pthread_mutex_t i2ctransport_mtx = PTHREAD_MUTEX_INITIALIZER;
55 
56 /**************************************************************************************************
57  *
58  *                                      Private API Declaration
59  *
60  **************************************************************************************************/
61 
62 static int i2cSetPolarity(int fid, bool low, bool edge);
63 static int i2cResetPulse(int fid);
64 static int i2cRead(int fid, uint8_t* pvBuffer, int length);
65 static int i2cGetGPIOState(int fid);
66 static int i2cWrite(int fd, const uint8_t* pvBuffer, int length);
67 
68 /**************************************************************************************************
69  *
70  *                                      Public API Entry-Points
71  *
72  **************************************************************************************************/
73 
74 /**
75  * Worker thread for I2C data processing.
76  * On exit of this thread, destroy the HAL thread instance.
77  * @param arg  Handle of the HAL layer
78  */
I2cWorkerThread(void * arg)79 static void* I2cWorkerThread(void* arg) {
80   bool closeThread = false;
81   HALHANDLE hHAL = (HALHANDLE)arg;
82   STLOG_HAL_V("echo thread started...\n");
83   bool readOk = false;
84 
85   do {
86     event_table[0].fd = fidI2c;
87     event_table[0].events = POLLIN;
88     event_table[0].revents = 0;
89 
90     event_table[1].fd = cmdPipe[0];
91     event_table[1].events = POLLIN;
92     event_table[1].revents = 0;
93 
94     STLOG_HAL_D("echo thread go to sleep...\n");
95 
96     int poll_status = poll(event_table, 2, -1);
97 
98     if (-1 == poll_status) {
99       STLOG_HAL_E("error in poll call\n");
100       return 0;
101     }
102 
103     if (event_table[0].revents & POLLIN) {
104       STLOG_HAL_D("echo thread wakeup from chip...\n");
105 
106       uint8_t buffer[300];
107 
108       do {
109         // load first four bytes:
110         int bytesRead = i2cRead(fidI2c, buffer, 3);
111 
112         if (bytesRead == 3) {
113           if ((buffer[0] != 0x7E) && (buffer[1] != 0x7E)) {
114             readOk = true;
115           } else {
116             if (buffer[1] != 0x7E) {
117               STLOG_HAL_W(
118                   "Idle data: 2nd byte is 0x%02x\n, reading next 2 bytes",
119                   buffer[1]);
120               buffer[0] = buffer[1];
121               buffer[1] = buffer[2];
122               bytesRead = i2cRead(fidI2c, buffer + 2, 1);
123               if (bytesRead == 1) {
124                 readOk = true;
125               }
126             } else if (buffer[2] != 0x7E) {
127               STLOG_HAL_W("Idle data: 3rd byte is 0x%02x\n, reading next  byte",
128                           buffer[2]);
129               buffer[0] = buffer[2];
130               bytesRead = i2cRead(fidI2c, buffer + 1, 2);
131               if (bytesRead == 2) {
132                 readOk = true;
133               }
134             } else {
135               STLOG_HAL_W("received idle data\n");
136             }
137           }
138 
139           if (readOk == true) {
140             int remaining = buffer[2];
141 
142             // read and pass to HALCore
143             bytesRead = i2cRead(fidI2c, buffer + 3, remaining);
144             if (bytesRead == remaining) {
145               DispHal("RX DATA", buffer, 3 + bytesRead);
146               HalSendUpstream(hHAL, buffer, 3 + bytesRead);
147             } else {
148               readOk = false;
149               STLOG_HAL_E("! didn't read expected bytes from i2c\n");
150             }
151           }
152 
153         } else {
154           STLOG_HAL_E("! didn't read 3 requested bytes from i2c\n");
155         }
156 
157         readOk = false;
158         memset(buffer, 0xca, sizeof(buffer));
159 
160         /* read while we have data available */
161       } while (i2cGetGPIOState(fidI2c) == 1);
162     }
163 
164     if (event_table[1].revents & POLLIN) {
165       STLOG_HAL_V("thread received command.. \n");
166 
167       char cmd = 0;
168       read(cmdPipe[0], &cmd, 1);
169 
170       switch (cmd) {
171         case 'X':
172           STLOG_HAL_D("received close command\n");
173           closeThread = true;
174           break;
175 
176         case 'W': {
177           size_t length;
178           uint8_t buffer[MAX_BUFFER_SIZE];
179           STLOG_HAL_V("received write command\n");
180           read(cmdPipe[0], &length, sizeof(length));
181           if (length <= MAX_BUFFER_SIZE) {
182             read(cmdPipe[0], buffer, length);
183             i2cWrite(fidI2c, buffer, length);
184           } else {
185             STLOG_HAL_E(
186                 "! received bigger data than expected!! Data not transmitted "
187                 "to NFCC \n");
188             size_t bytes_read = 1;
189             // Read all the data to empty but do not use it as not expected
190             while ((bytes_read > 0) && (length > 0)) {
191               bytes_read = read(cmdPipe[0], buffer, MAX_BUFFER_SIZE);
192               length = length - bytes_read;
193             }
194           }
195         } break;
196       }
197     }
198 
199   } while (!closeThread);
200 
201   close(fidI2c);
202   close(cmdPipe[0]);
203   close(cmdPipe[1]);
204 
205   HalDestroy(hHAL);
206   STLOG_HAL_D("thread exit\n");
207   return 0;
208 }
209 
210 /**
211  * Put command into queue for worker thread to process it.
212  * @param x Command 'X' to close I2C layer or 'W' to write data down to I2C
213  * layer followed by data frame
214  * @param len Size of command or data
215  * @return
216  */
I2cWriteCmd(const uint8_t * x,size_t len)217 int I2cWriteCmd(const uint8_t* x, size_t len) {
218   return write(cmdPipe[1], x, len);
219 }
220 
221 /**
222  * Initialize the I2C layer.
223  * @param dev NFC NCI device context, NFC callbacks for control/data, HAL handle
224  * @param callb HAL Core callback upon reception on I2C
225  * @param pHandle HAL context handle
226  */
I2cOpenLayer(void * dev,HAL_CALLBACK callb,HALHANDLE * pHandle)227 bool I2cOpenLayer(void* dev, HAL_CALLBACK callb, HALHANDLE* pHandle) {
228   uint32_t NoDbgFlag = HAL_FLAG_DEBUG;
229 
230   (void)pthread_mutex_lock(&i2ctransport_mtx);
231   fidI2c = open("/dev/st21nfc", O_RDWR);
232   if (fidI2c < 0) {
233     STLOG_HAL_W("unable to open /dev/st21nfc\n");
234     return false;
235   }
236 
237   i2cSetPolarity(fidI2c, false, true);
238   i2cResetPulse(fidI2c);
239 
240   if ((pipe(cmdPipe) == -1)) {
241     STLOG_HAL_W("unable to open cmdpipe\n");
242     return false;
243   }
244 
245   *pHandle = HalCreate(dev, callb, NoDbgFlag);
246 
247   if (!*pHandle) {
248     STLOG_HAL_E("failed to create NFC HAL Core \n");
249     return false;
250   }
251 
252   (void)pthread_mutex_unlock(&i2ctransport_mtx);
253 
254   return (pthread_create(&threadHandle, NULL, I2cWorkerThread, *pHandle) == 0);
255 }
256 
257 /**
258  * Terminates the I2C layer.
259  */
I2cCloseLayer()260 void I2cCloseLayer() {
261   uint8_t cmd = 'X';
262   int ret;
263   ALOGD("%s: enter\n", __func__);
264 
265   (void)pthread_mutex_lock(&i2ctransport_mtx);
266 
267   if (threadHandle == (pthread_t)NULL) return;
268 
269   I2cWriteCmd(&cmd, sizeof(cmd));
270   /* wait for terminate */
271   ret = pthread_join(threadHandle, (void**)NULL);
272   if (ret != 0) {
273     ALOGE("%s: failed to wait for thread (%d)", __func__, ret);
274   }
275   threadHandle = (pthread_t)NULL;
276   (void)pthread_mutex_unlock(&i2ctransport_mtx);
277 }
278 /**************************************************************************************************
279  *
280  *                                      Private API Definition
281  *
282  **************************************************************************************************/
283 /**
284  * Call the st21nfc driver to adjust wake-up polarity.
285  * @param fid File descriptor for NFC device
286  * @param low Polarity (HIGH or LOW)
287  * @param edge Polarity (RISING or FALLING)
288  * @return Result of IOCTL system call (0 if ok)
289  */
i2cSetPolarity(int fid,bool low,bool edge)290 static int i2cSetPolarity(int fid, bool low, bool edge) {
291   int result;
292   unsigned int io_code;
293 
294   if (low) {
295     if (edge) {
296       io_code = ST21NFC_SET_POLARITY_FALLING;
297     } else {
298       io_code = ST21NFC_SET_POLARITY_LOW;
299     }
300 
301   } else {
302     if (edge) {
303       io_code = ST21NFC_SET_POLARITY_RISING;
304     } else {
305       io_code = ST21NFC_SET_POLARITY_HIGH;
306     }
307   }
308 
309   if (-1 == (result = ioctl(fid, io_code, NULL))) {
310     result = -1;
311   }
312 
313   return result;
314 } /* i2cSetPolarity*/
315 
316 /**
317  * Call the st21nfc driver to generate a 30ms pulse on RESET line.
318  * @param fid File descriptor for NFC device
319  * @return Result of IOCTL system call (0 if ok)
320  */
i2cResetPulse(int fid)321 static int i2cResetPulse(int fid) {
322   int result;
323 
324   if (-1 == (result = ioctl(fid, ST21NFC_PULSE_RESET, NULL))) {
325     result = -1;
326   }
327   STLOG_HAL_D("! i2cResetPulse!!, result = %d", result);
328   return result;
329 } /* i2cResetPulse*/
330 
331 /**
332  * Write data to st21nfc, on failure do max 3 retries.
333  * @param fid File descriptor for NFC device
334  * @param pvBuffer Data to write
335  * @param length Data size
336  * @return 0 if bytes written, -1 if error
337  */
i2cWrite(int fid,const uint8_t * pvBuffer,int length)338 static int i2cWrite(int fid, const uint8_t* pvBuffer, int length) {
339   int retries = 0;
340   int result = 0;
341 
342   while (retries < 3) {
343     result = write(fid, pvBuffer, length);
344 
345     if (result < 0) {
346       char msg[LINUX_DBGBUFFER_SIZE];
347 
348       strerror_r(errno, msg, LINUX_DBGBUFFER_SIZE);
349       STLOG_HAL_W("! i2cWrite!!, errno is '%s'", msg);
350       usleep(4000);
351       retries++;
352     } else if (result > 0) {
353       result = 0;
354       return result;
355     } else {
356       STLOG_HAL_W("write on i2c failed, retrying\n");
357       usleep(4000);
358       retries++;
359     }
360   }
361 
362   return -1;
363 } /* i2cWrite */
364 
365 /**
366  * Read data from st21nfc, on failure do max 3 retries.
367  *
368  * @param fid File descriptor for NFC device
369  * @param pvBuffer Buffer where to copy read data
370  * @param length Data size to read
371  * @return Length of read data, -1 if error
372  */
i2cRead(int fid,uint8_t * pvBuffer,int length)373 static int i2cRead(int fid, uint8_t* pvBuffer, int length) {
374   int retries = 0;
375   int result = -1;
376 
377   while ((retries < 3) && (result < 0)) {
378     result = read(fid, pvBuffer, length);
379 
380     if (result == -1) {
381       int e = errno;
382       if (e == EAGAIN) {
383         /* File is nonblocking, and no data is available.
384          * This is not an error condition!
385          */
386         result = 0;
387         STLOG_HAL_D(
388             "## i2cRead - got EAGAIN. No data available. return 0 bytes");
389       } else {
390         /* unexpected result */
391         char msg[LINUX_DBGBUFFER_SIZE];
392         strerror_r(e, msg, LINUX_DBGBUFFER_SIZE);
393         STLOG_HAL_W("## i2cRead returns %d errno %d (%s)", result, e, msg);
394       }
395     }
396 
397     if (result < 0) {
398       if (retries < 3) {
399         /* delays are different and increasing for the three retries. */
400         static const uint8_t delayTab[] = {2, 3, 5};
401         int delay = delayTab[retries];
402 
403         retries++;
404         STLOG_HAL_W("## i2cRead retry %d/3 in %d milliseconds.", retries,
405                     delay);
406         usleep(delay * 1000);
407         continue;
408       }
409     }
410   }
411   return result;
412 } /* i2cRead */
413 
414 /**
415  * Get the activation status of wake-up pin from st21nfc.
416  *  The decision 'active' depends on selected polarity.
417  *  The decision is handled inside the driver(st21nfc).
418  * @param fid File descriptor for NFC device
419  * @return
420  *  Result < 0:     Error condition
421  *  Result > 0:     Pin active
422  *  Result = 0:     Pin not active
423  */
i2cGetGPIOState(int fid)424 static int i2cGetGPIOState(int fid) {
425   int result;
426 
427   if (-1 == (result = ioctl(fid, ST21NFC_GET_WAKEUP, NULL))) {
428     result = -1;
429   }
430 
431   return result;
432 } /* i2cGetGPIOState */
433