Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / Internet of things / goam / main / ptc06.c
blob: 00efa768505137334cc4e65c0219ac59fc439b81 (plain) (blame)
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/uart.h"
#include "esp_log.h"
/* #include "esp_check.h" */

#include "ptc06.h"
#include "display.h"
#include "sdkconfig.h"
#include <string.h>

/*
 * Helpers
 */

static void append(char* container, const char* data, size_t dataLen) {
	for (size_t i = 0; i < dataLen; i++)
		container[i] = data[i];
}

static size_t arr2ToNum(const char arr[2]) {
	return (arr[0] << 8) | arr[1];
}

static size_t arr4ToNum(const char arr[4]) {
	return (arr2ToNum(arr) << 16) | arr2ToNum(arr+2);
}

#define min(a, b) (a < b) ? (a) : (b)

/*
 * Logging
 */

static const char* TAG = "ptc06";

static void debug_print(const char* prepend, char* message, size_t size) {
	if (esp_log_level_get(TAG) < ESP_LOG_DEBUG) return;

	printf("%s: %s ", TAG, prepend);
	for (int i = 0; i < size; i++) {
		printf("%X ", message[i]);
	}
	printf("\n");
}

/*
 * UART settings
 */

#define UART_NUM UART_NUM_2
#define UART_BUFFER_SIZE 16 * 1024

// Setup UART buffered IO with event queue
static QueueHandle_t uart_queue;
#define QUEUE_SIZE 10

static size_t serial_num = 0x00;

static void init_uart_interface() {
	// HS_UART
	uart_config_t uart_config = {
		.baud_rate = 115200,
		.data_bits = UART_DATA_8_BITS,
		.parity    = UART_PARITY_DISABLE,
		.stop_bits = UART_STOP_BITS_1,
		.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
		.source_clk = UART_SCLK_DEFAULT,
	};
	// Configure UART parameters
	ESP_ERROR_CHECK(uart_param_config(UART_NUM, &uart_config));

	// Set UART pins(TX: IO17 (UART2 default), RX: IO16 (UART2 default), RTS: IO18, CTS: IO19)
	ESP_ERROR_CHECK(uart_set_pin(UART_NUM, CONFIG_CAM_TX_PIN, CONFIG_CAM_RX_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));

	// Install UART driver using an event queue
	ESP_ERROR_CHECK(uart_driver_install(UART_NUM, UART_BUFFER_SIZE, UART_BUFFER_SIZE, QUEUE_SIZE, &uart_queue, 0));

	uart_flush(UART_NUM);
}

// On init, the UART may be full of data and the camera may be outputting data to it.
// So the flush command isn't entirely effective, with this function we make sure it is clean,
// even if we take a time penalty.
//
// It also seems that these wait periods are the perfect values, anything less and it has failed.
static void dynamic_flush_uart() {
	vTaskDelay(pdMS_TO_TICKS(500));
	size_t length;
	ESP_ERROR_CHECK(uart_get_buffered_data_len(UART_NUM, &length));
	while (length > 0) {
		uart_flush(UART_NUM);
		vTaskDelay(pdMS_TO_TICKS(1000));
		ESP_ERROR_CHECK(uart_get_buffered_data_len(UART_NUM, &length));
	}
}

/*
 * Generic UART communiction
 */

enum Command {
	GEN_VERSION       = 0x11, // Not implemented
	SET_SERIAL_NUMBER = 0x21, // Not implemented
	SET_PORT          = 0x24, // Not implemented
	SYSTEM_RESET      = 0x26,

	READ_DATA    = 0x30, // Not implemented
	WRITE_DATA   = 0x31,
	READ_FBUF    = 0x32,
	WRITE_FBUF   = 0x33, // Not implemented
	GET_FBUF_LEN = 0x34,
	SET_FBUF_LEN = 0x35, // Not implemented
	FBUF_CTRL    = 0x36,

	COMM_MOTION_CTRL     = 0x37, // Not implemented
	COMM_MOTION_STATUS   = 0x38, // Not implemented
	COMM_MOTION_DETECTED = 0x39, // Not implemented
	MIRROR_CTRL          = 0x3A, // Not implemented
	MIRROR_STATUS        = 0x3B, // Not implemented
	COLOR_CTRL           = 0x3C, // Not implemented
	COLOR_STATUS         = 0x3D, // Not implemented
	POWER_SAVE_CTRL      = 0x3E, // Not implemented
	POWER_SAVE_STATUS    = 0x3F, // Not implemented

	AE_CTRL         = 0x40, // Not implemented
	AE_STATUS       = 0x41, // Not implemented
	MOTION_CTRL     = 0x42, // Not implemented
	MOTION_STATUS   = 0x43, // Not implemented
	TV_OUT_CTRL     = 0x44, // Not implemented
	OSD_ADD_CHAR    = 0x45, // Not implemented
	DOWNSIZE_CTRL   = 0x54, // Not implemented
	DOWNSIZE_STATUS = 0x55, // Not implemented

	GET_FLASH_SIZE     = 0x60, // Not implemented
	ERASE_FLASH_SECTOR = 0x61, // Not implemented
	ERASE_FLASH_ALL    = 0x62, // Not implemented
	READ_LOGO          = 0x70, // Not implemented
	SET_BITMAP         = 0x71, // Not implemented
	BATCH_WRITE        = 0x80  // Not implemented
};

static void send(enum Command comm_byte, const char data_lengths, char data[16]) {
	// Format:
	// Protocol sign (1byte) + Serial number (1byte) + Command (1byte) + Data-lengths (1byte) + Data (0~16bytes)
	char command[20] = { 0x56, serial_num, comm_byte, data_lengths, };
	append(command + 4, data, data_lengths);

	debug_print("sent", command, 4+data_lengths);

	uart_write_bytes(UART_NUM, command, 4 + data_lengths);
	ESP_ERROR_CHECK(uart_wait_tx_done(UART_NUM, 100)); // if it takes too long, then we have communication issues
}

#define byte_check(errmsg, compare) \
	if (!(compare)) {                               \
		ESP_LOGE(TAG, "Invalid response, " errmsg); \
		display_printat(DCHAR_NO_CAMERA_EXCLAM,     \
		                CONFIG_DISPLAY_ICONS_ROW,   \
		                CONFIG_CAMERA_COLUMN);      \
	}

static void recv(enum Command comm_byte, const char expectedDataSize, char ack[21]) {
	// Format:
	// Protocol sign (1byte) + Serial number (1byte) + Command (1byte) + Status (1byte) + Data-lengths (1byte) + Data (0~16bytes)
	uart_read_bytes(UART_NUM, ack, 5 + expectedDataSize, 100);
	ESP_ERROR_CHECK(uart_wait_tx_done(UART_NUM, 100));

	debug_print("recv", ack, 5+expectedDataSize);

	byte_check("BAD_RETURN_SIGN",    ack[0] == 0x76);
	byte_check("BAD_SERIAL_NUM",     ack[1] == serial_num);
	byte_check("BAD_RETURN_COMMAND", ack[2] == comm_byte);
	byte_check("BAD_RETURN_STATUS",  ack[3] == 0);
	// ack[4] is data-lengths, no need to check
}

/*
 * VC0706 command implementation
 */

static char temp_ack[21], temp_data[16];

static void vc0706_system_reset() {
	dynamic_flush_uart();
	send(SYSTEM_RESET, 0, NULL);
	recv(SYSTEM_RESET, 0, temp_ack);
	vTaskDelay(pdMS_TO_TICKS(20));
	dynamic_flush_uart(); // ignore "basic configuration information"
}

enum ControlFlag {
	STOP_CURRENT_FRAME = 0x00,
	STOP_NEXT_FRAME    = 0x01,
	RESUME_FRAME       = 0x02,
	STEP_FRAME         = 0x03
};

static void vc0706_fbuf_ctrl(enum ControlFlag cf_byte) {
	temp_data[0] = cf_byte;
	send(FBUF_CTRL, 0x01, temp_data);
	recv(FBUF_CTRL, 0, temp_ack);
}

enum FBufType {
	CURRENT_FRAME = 0,
	NEXT_FRAME    = 1
};

static void vc0706_get_fbuf_len(enum FBufType fbt_byte) {
	temp_data[0] = fbt_byte;
	send(GET_FBUF_LEN, 0x01, temp_data);
	recv(GET_FBUF_LEN, 4, temp_ack);
}

enum ControlMode {
	MCU = 0xFE,
	DMA = 0x0A
};

static size_t vc0706_read_fbuf(enum FBufType fbt_byte, enum ControlMode cm_byte, const char start[4], const char data_length[4], const char delay[2], char** image) {
	size_t delayby = arr2ToNum(delay);
	size_t length  = arr4ToNum(data_length);

	*image = (char*)malloc(length);
	memset(*image, 0xFA, length); // So it's easily recogniseable if the whole array wasn't filled with anything

	temp_data[0] = fbt_byte;
	temp_data[1] = cm_byte;
	append(temp_data +  2, start,       4);
	append(temp_data +  6, data_length, 4);
	append(temp_data + 10, delay,       2);

	send(READ_FBUF, 0x0C, temp_data);

	recv(READ_FBUF, 0, temp_ack);
	vTaskDelay(pdMS_TO_TICKS(delayby * 0.01 * 2));

	size_t current = 0;
	size_t available = 1;
	while (current < length) {
		ESP_ERROR_CHECK(uart_get_buffered_data_len(UART_NUM, &available));
		/* size_t old = current; */
		current += uart_read_bytes(UART_NUM, *image + current, min(available, length - current), 500);
		ESP_ERROR_CHECK(uart_wait_tx_done(UART_NUM, 500));
		vTaskDelay(pdMS_TO_TICKS(20));
	}

	vTaskDelay(pdMS_TO_TICKS(delayby * 0.01 * 2));
	recv(READ_FBUF, 0, temp_ack);

	return length;
}

enum DeviceType {
	CHIP_REGISTER    = 0x01,
	SENSOR_REGISTER  = 0x02,
	CCIR656_REGISTER = 0x03,
	I2C_EEPROM       = 0x04,
	SPI_EEPROM       = 0x05,
	SPI_FLASH        = 0x06
};

static char temp_configuration[4];
static char temp_write_data[14];

static void vc0706_write_data(enum DeviceType dt_byte, char write_data_len, const char configuration[4], const char write_data[14]) {
	size_t configuration_size = 2;
	if (dt_byte == SENSOR_REGISTER || dt_byte == CCIR656_REGISTER) configuration_size = 3;
	if (dt_byte == SPI_FLASH) configuration_size = 4;

	temp_data[0] = dt_byte;
	temp_data[1] = write_data_len;
	append(temp_data + 2,                      configuration, configuration_size);
	append(temp_data + 2 + configuration_size, write_data,    write_data_len);

	send(WRITE_DATA, 2 + configuration_size + write_data_len, temp_data);
	recv(WRITE_DATA, 0, temp_ack);
}

/*
 * PTC06 camera module commands
 */

static void init_camera() {
	vTaskDelay(pdMS_TO_TICKS(2500));
}

/*
 * Public interface
 */

void ptc06_init() {
	init_camera();
	init_uart_interface();
	vc0706_system_reset();

	/* ptc06_set_resolution(); */
	/* ptc06_set_compressibility(); */

	ESP_LOGI(TAG, "Initialized ptc06 successfully. UART tx: %d, rx: %d", CONFIG_CAM_TX_PIN, CONFIG_CAM_RX_PIN);
}

void ptc06_reset() {
	vc0706_system_reset();
}

size_t ptc06_get_image(char** image) {
	vc0706_fbuf_ctrl(STOP_CURRENT_FRAME);
	vTaskDelay(pdMS_TO_TICKS(500));

	vc0706_get_fbuf_len(CURRENT_FRAME);
	char start[4] = { 0x00 };
	char delay[2] = { 0x30, 0x00 };
	size_t length = vc0706_read_fbuf(CURRENT_FRAME, DMA, start, temp_ack + 5, delay, image);

	vc0706_fbuf_ctrl(RESUME_FRAME);
	vc0706_system_reset(); // Practice has shown this is mandatory
	return length;
}

void ptc06_set_image_resolution(enum Resolution res) {
	temp_configuration[0] = 0x00;
	temp_configuration[1] = 0x19;
	temp_write_data[0] = res;
	vc0706_write_data(I2C_EEPROM, 0x01, temp_configuration, temp_write_data);
	vc0706_system_reset(); // Practice has shown this is mandatory
}



/*
static void ptc06_set_resolution() {
	char res[] = { 0x22 };
	send_commVARS(comm_set_res, res);
	recv_ack(resp_set_res);
	fully_flush_uart();
}

static void ptc06_set_compressibility() {
	char compr[] = { 0xFF };
	send_commVARS(comm_set_compress, compr);
	recv_ack(resp_set_compress);
	fully_flush_uart();
}

static void ptc06_capture() {
	send_comm(comm_capture);
	recv_ack(resp_capture);
	fully_flush_uart();
	ESP_LOGI(TAG, "Captured");
}

static void ptc06_read_image_length(char* XX, char* YY) {
	send_comm(comm_data_len);
	recv_ackXXYY(resp_data_len, XX, YY);
	fully_flush_uart();
	ESP_LOGI(TAG, "Read length");
}

char* ptc06_shoot_photo() {
	ptc06_capture();
	char XX, YY;
	ptc06_read_image_length(&XX, &YY);
	char* img = ptc06_read_image_data(XX, YY);
	ptc06_stop_capture();
	return img;
}
*/