summaryrefslogtreecommitdiff
path: root/src/arch/posix/driver/i2c.cc
blob: cf08a7731a13d0115f7330d78e875ffc8fef87c2 (plain)
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
/*
 * Copyright 2021 Birte Kristina Friesel
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */
#include "driver/i2c.h"
#include "arch.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <i2c/smbus.h>

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define I2C_BUS TOSTRING(CONFIG_arch_posix_driver_i2c_bus)

signed char I2C::setup()
{
	return 0;
}

signed char I2C::xmit(unsigned char address,
		unsigned char tx_len, unsigned char *tx_buf,
		unsigned char rx_len, unsigned char *rx_buf)
{
	struct i2c_msg messages[2];
	struct i2c_rdwr_ioctl_data transaction;
	transaction.nmsgs = 0;
	transaction.msgs = messages;

	if (tx_len) {
		messages[transaction.nmsgs].addr = address;
		messages[transaction.nmsgs].flags = 0;
		messages[transaction.nmsgs].len = tx_len;
		messages[transaction.nmsgs].buf = tx_buf;
		transaction.nmsgs++;
	}
	if (rx_len) {
		messages[transaction.nmsgs].addr = address;
		messages[transaction.nmsgs].flags = I2C_M_RD;
		messages[transaction.nmsgs].len = rx_len;
		messages[transaction.nmsgs].buf = rx_buf;
		transaction.nmsgs++;
	}

	int fh = open(i2cbus, O_RDWR);

	if (fh < 0) {
		return -1;
	}

	if (ioctl(fh, I2C_RDWR, &transaction) == -1) {
		return -1;
	}

	close(fh);
	return 0;
}

I2C i2c(I2C_BUS);