1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/* hardware interface struct
 * functions are defined in target tree
 */
struct i2c_struct
{
    int  (*i2c_start)(void);
    void (*i2c_stop)(void);
    int  (*i2c_outb)(unsigned char byte)
    int  (*i2c_inb)(bool ack);
    void (*i2c_hw_init)(void);
}

/* arbitrary choosen */
#define  MAX_I2C_INTERFACES 5
/* global array which holds ptrs to struct with lowlevel,
 * platform specific i2c functions
 */
static const struct i2c_struct *i2c_if[MAX_I2C_INTERFACES];

int i2c_write (int bus_index,
               unsigned char i2c_addr,
               int address,
               const unsigned char *buf,
               int count)
{
    int i;
    int ret = 0;
    const struct i2c_struct *iface = i2c_if[bus_index];

    iface->i2c_start();
    if (!iface->i2c_outb(i2c_address & 0xfe))
    {
        ret = -2;
        goto end;
    }

    if (address != -1)
    {
        if (!iface->i2c_outb(address))
        {
            ret = -3;
            goto end;
        }
    }

    for(i = 0;i < count;i++)
    {
        if (!iface->i2c_outb(buf[i]))
        {
            ret = -4;
            break;
        }
    }

end:
    iface->i2c_stop();
    return ret;
}

int i2c_write (int bus_index,
               unsigned char i2c_addr,
               int address,
               const unsigned char *buf,
               int count)
{  
    int i;
    int ret = 0;
    const struct i2c_struct *iface = i2c_if[bus_index];

    if (address != -1)
    {
        iface->i2c_start();
        if (!iface->i2c_outb(bus_address & 0xfe))
        {
            ret = -2;
            goto end;
        }
        if (!iface->i2c_outb(address))
        {
            ret = -3;
            goto end;
        }
    }

    iface->i2c_start();
    if (!iface->i2c_outb(bus_address | 1))
    {
        ret = -4;
        goto end;
    }

    for(i = 0;i < count-1;i++)
        buf[i] = iface->i2c_inb(true);

    buf[i] = iface->i2c_inb(false);

end:
    iface->i2c_stop();
    return ret;
}

int i2c_register_interface(int bus_index
                           struct i2c_struct *iface)
{
    static unsigned char i2c_num_ifs = 0;

    if ( bus_index < 0 )
    {
        /* assign next free index */
        if (i2c_num_ifs == MAX_I2C_INTERFACES)
            return -1;

        bus_index = i2c_num_ifs++;
    }

    i2c_if[bus_index] = iface;
}

void i2c_init(void)
{
    int i;
    struct i2c_struct *iface;

    for (i=0; i < MAX_I2C_INTERFACES; i++)
    {
        if (i2c_if[i] != NULL)
        {
            iface = i2c_if[i];
            i2c_if->i2c_hw_init();
        }
    }
}