I2C communication

most of the case when we communicate with a I2C driver
we prepare a unsigned char buffer to read/write to the I2C file node, since we cannot know the data read/write is positive or negative, so unsigned is the only way to store the value
and also we cannot know the order of the data(little endian or big endian), so char prevent us from doing miss-order

...
typedef struct {
        unsigned char func;
        unsigned char buffer[8];
} S_SensoryLicense;
...
uint32_t *securityChipComms(uint32_t * challenge)
{
        size_t ret = 0;
        int fd = 0;
        S_SensoryLicense SensoryLicense;
        static uint32_t respond[2];

        if (NULL == challenge) {
                printf("challenge is NULL\n");
                return (void *)-1;
        }

        /*
         * do the hardware communication with security IC
         * send challenge to IC
         * get respond from IC and place in 'respond'
         */
        fd = open(I2C_DEVICE_NAME, O_RDWR);
        if (fd < 0) {
                printf("open %s failed\n", I2C_DEVICE_NAME);
                return (void *)-1;
        }
        SensoryLicense.func = CHIP_WRITE;
        memcpy(&SensoryLicense.buffer, challenge, sizeof(uint32_t) * 2);
        ret = write(fd, &SensoryLicense, sizeof(SensoryLicense));
        if (ret < 0) {
                printf("write %s failed: %s\n", I2C_DEVICE_NAME, strerror(errno));
                return (void *)-1;
        }
        /*
         * userspace prepare a 9 bytes unsigned char array
         * sensory_ic read the 0th bytes for register address
         * then sensory_ic copy respond to 0th of the array
         */
        SensoryLicense.func = CHIP_READ;
        ret = read(fd, &SensoryLicense, sizeof(SensoryLicense));
        memcpy(respond, &SensoryLicense, sizeof(SensoryLicense.buffer));
        if (ret < 0) {
                printf("read %s failed: %s\n", I2C_DEVICE_NAME, strerror(errno));
                return (void *)-1;
        }
        close(fd);
        return respond;
}

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Google photo

您的留言將使用 Google 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s