summaryrefslogtreecommitdiffstats
path: root/usb/endpt1.c
blob: dcfc61b3c1cb35e5d12783aee26c9d7d779072a2 (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
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
/*
 * usb/endpt1.c -- USB endpoit 1 (HID) handling
 *
 * Copyright (C) 2016-2017 Tomasz Kramkowski <tk@the-tk.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <reg/usbotg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>

#include <reg/gpio.h>

#include "../uart.h"

#include "bdt.h"
#include "endpt1.h"
#include "keycodes.h"
#include "txhandler.h"

#define MAX_PACKET 64

static struct tx_ctx tx;
#define THIS_EP 1
static volatile struct usb0_bd (* const this_bdt)[2] = usb_bdt[THIS_EP];

unsigned char report[29];
volatile bool sendrep;

void usb_endpt1_setkey(enum keycode keycode, bool state)
{
	unsigned char byte, bit;

	if (keycode == KEY_NONE)
		return;

	keycode -= 4;
	byte = keycode / 8;
	bit = keycode % 8;

	if (state)
		SET_BIT(report[byte], bit);
	else
		UNSET_BIT(report[byte], bit);

	sendrep = true;
}

void usb_endpt1_send(void)
{
	if (!sendrep)
		return;
	if (!tx_isempty(&tx)) {
		return;
	}

	tx_que(&tx, report, sizeof report);
	sendrep = false;
}

void usb_endpt1_enable(void)
{
	this_bdt[BDT_TX][BDT_EVEN].addr = NULL;
	this_bdt[BDT_TX][BDT_EVEN].desc = 0;

	this_bdt[BDT_TX][BDT_ODD].addr = NULL;
	this_bdt[BDT_TX][BDT_ODD].desc = 0;

	USB0_ENDPT(THIS_EP) = BV(ENDPT_EPTXEN) | BV(ENDPT_EPHSHK);
	tx = TX_CTX(this_bdt[BDT_TX], MAX_PACKET);
	tx_que(&tx, report, sizeof report);
}

void usb_endpt1_disable(void)
{
	USB0_ENDPT(THIS_EP) = 0;
}

void usb_endpt1_token(uint8_t state)
{
	volatile struct usb0_bd *bd;

	bd = &usb_bdt[1][GET_BIT(state, STAT_TX)][GET_BIT(state, STAT_ODD)];

	switch (GET_BITS(bd->desc, BD_TOK_PID)) {
	case BD_TOK_PID_IN:
		tx_push(&tx);
		break;
	}
}