File: libusbrelay.c

package info (click to toggle)
usbrelay 1.0-2.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 740 kB
  • sloc: ansic: 618; python: 100; makefile: 58; xml: 25; sh: 5
file content (378 lines) | stat: -rw-r--r-- 10,205 bytes parent folder | download | duplicates (2)
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
370
371
372
373
374
375
376
377
378
/*
libusbrelay: Control USB HID connected electrical relay modules
Copyright (C) 2014  Darryl Bond
Library version
Copyright (C) 2019  Sean Mollet

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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <stdio.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <hidapi/hidapi.h>
#include "libusbrelay.h"
#include "gitversion.h"

//Global variables

relay_board *relay_boards = 0;
int relay_board_count = 0;
int i, k;
const char *libversion = GITVERSION;

//Private function prototypes
static int get_board_features(relay_board * board, hid_device * handle);
int known_relay(struct hid_device_info *thisdev);

/**
 * Enumerate all possible relay devices in the system
 */
const char * libusbrelay_version(void){
	return libversion;
}
int enumerate_relay_boards(const char *product, int verbose, int debug)
{

	int result = 0, relay = 0;
	struct hid_device_info *devs, *cur_dev;
	int num_opened = 0, num_error = 0;
	//Enumerate all HID USB devices 
	devs = hid_enumerate(0, 0);

	//Count the number of returned devices
	cur_dev = devs;
	// if (debug) fprintf(stderr,"Library Version: %s\n",libversion);

	while (cur_dev != NULL) {
		// Check if the HID device is a known relay else jump over it
		if (known_relay(cur_dev)) {
			relay_board_count++;
		}
		cur_dev = cur_dev->next;
	}
	if (debug)
		fprintf(stderr,"enumerate_relay_boards()Found %d devices\n", relay_board_count);

	//Allocate a buffer for the relays
	if (relay_board_count > 0) {
		relay_boards = calloc(relay_board_count, sizeof(relay_board));

		//Fill the relay structs
		cur_dev = devs;
		while (cur_dev != NULL) {
			// skip unknown HID devices
			relay_boards[relay].module_type = known_relay(cur_dev);
			if (relay_boards[relay].module_type) {
				//Save the path to this device
				relay_boards[relay].path =
				    malloc(strlen(cur_dev->path) + 1);
				memcpy(relay_boards[relay].path, cur_dev->path,
				       strlen(cur_dev->path) + 1);

				
				// Ucreatefun relays do not have any information returned from the HID report
				// The USB serial is also fixed so this is copied to the module serial so that something can make the module unique
				if (relay_boards[relay].module_type == UCREATE) {
					relay_boards[relay].relay_count = 9;	//No way of finding number of relays for these boards
					memset(relay_boards[relay].serial, 0x0,
					       sizeof(relay_boards[relay].serial));
					wcstombs(relay_boards[relay].serial,
						 cur_dev->serial_number,
						 Serial_Length);
				} else {
					// The product string is USBRelayx where x is number of relays read to the \0 in case there are more than 9
					relay_boards[relay].relay_count = atoi((const char *)&cur_dev->product_string[8]);
				}
				//Open it to get more details
				hid_device *handle;
				handle = hid_open_path(cur_dev->path);
				if (handle) {
					num_opened++;
					result = get_board_features(&relay_boards[relay], handle);
					hid_close(handle);
				} else {
					num_error++;
					perror(cur_dev->path);
					result = -1;
				}

				//Output the device enumeration details if debug is on
				if (result != -1 && debug) {
					fprintf(stderr,"Device Found\n  type: %04hx %04hx\n  path: %s\n  serial_number: %s\n",
						cur_dev->vendor_id,
						cur_dev->product_id,
						relay_boards[relay].path,
						relay_boards[relay].serial);
					fprintf(stderr,"Manufacturer: %ls\n  Product:      %ls\n  Release:      %hx\n  Interface:    %d\n  Number of Relays = %d\n  Module_type = %d\n",
						cur_dev->manufacturer_string,
						cur_dev->product_string,
						cur_dev->release_number,
						cur_dev->interface_number,
						relay_boards[relay].relay_count,
						relay_boards[relay].module_type);
				}

				
				if (result != -1 && (verbose||debug)) {

					for (k = 0;k < relay_boards[relay].relay_count; k++) {
						if (relay_boards[relay].module_type == UCREATE)	{ // State cannot be determined print -1
							printf("%s_%d=-1\n",
									relay_boards[relay].serial,k + 1);
						} else {		 	
							if (relay_boards[relay].state & 1 << k) {
								printf("%s_%d=1\n",
									relay_boards[relay].serial,k + 1);
							} else {
								printf("%s_%d=0\n",
									relay_boards[relay].serial,k +1);
							}
						}
					}
				}
				relay++;
			}
			do {
				cur_dev = cur_dev->next;
			} while (cur_dev != NULL && !known_relay(cur_dev));
		}
	}
	hid_free_enumeration(devs);
	if (num_opened == 0 && num_error > 0)
		fprintf(stderr, "Unable to open any device - Use root, sudo or set the device permissions via udev\n");
	return result;
}

/**
 * Command a relay at a particular /dev path to switch to a given state
 */
int operate_relay(const char *serial, unsigned char relay,
		  unsigned char target_state,int debug)
{
	unsigned char buf[9];	// 1 extra byte for the report ID
	int res = -1;
	hid_device *handle;

	relay_board *board = find_board(serial,debug);
	if (board != NULL && relay > 0 ) { 
		if(debug) fprintf(stderr,"operate_relay(%s,%c) %s path\n",serial,relay, board->path );
		handle = hid_open_path(board->path);

		if (handle) {
			if (board->module_type == DCTTECH) {
				buf[0] = 0x0;	//report number
				buf[1] = target_state;
				buf[2] = relay;
				buf[3] = 0x00;
				buf[4] = 0x00;
				buf[5] = 0x00;
				buf[6] = 0x00;
				buf[7] = 0x00;
				buf[8] = 0x00;
				if ( relay == 9 ) { // operate all relays
					for (char i = 1; i <= board->relay_count; i++ ) {
						buf[2] = i;
						res = hid_write(handle, buf, sizeof(buf));
					}
				} else {
					if ( relay <= board->relay_count)
						res = hid_write(handle, buf, sizeof(buf));
				}
			}
			if (board->module_type == UCREATE) {

				unsigned char ucreate;
				if (target_state == 0xff)
					ucreate = 0xF0;
				else
					ucreate = 0x00;
				ucreate += relay;
				buf[0] = 0;	//report number
				buf[1] = ucreate;
				buf[2] = 0x00;
				buf[3] = 0x00;
				buf[4] = 0x00;
				buf[5] = 0x00;
				buf[6] = 0x00;
				buf[7] = 0x00;
				buf[8] = 0x00;
				res = hid_write(handle, buf, sizeof(buf));
			}
		} else {
			res = -1;
		}

		if (res > 0) {
			if (board->module_type == DCTTECH)
				//Update our relay status
				res = get_board_features(board, handle);
		} else {
			fprintf(stderr, "operate_relay() Unable to write or unknown relay\n");
			fprintf(stderr, "Error: %ls\n", hid_error(handle));
		}

		hid_close(handle);
	}

	return (res);
}

int set_serial(const char *serial, char *newserial,int debug)
{
	unsigned char buf[9];	// 1 extra byte for the report ID
	int res = -1;
	hid_device *handle;

	relay_board *board = find_board(serial,debug);
	if (board != NULL) {
		handle = hid_open_path(board->path);

		if (handle) {
			buf[0] = 0x0;	//report number
			buf[1] = CMD_SET_SERIAL;
			buf[2] = newserial[0];
			buf[3] = newserial[1];
			buf[4] = newserial[2];
			buf[5] = newserial[3];
			buf[6] = newserial[4];
			buf[7] = 0x00;
			buf[8] = 0x00;
			res = hid_write(handle, buf, sizeof(buf));
		} else {
			res = -1;
		}

		if (res > 0) {
			//Update our copy of the serial number
			res = get_board_features(board, handle);
		} else {
			fprintf(stderr, "set_serial() Unable to write()\n");
			fprintf(stderr, "Error: %ls\n", hid_error(handle));
		}
		hid_close(handle);
	}

	return (res);
}

/**
 * Find a board path given a relay board serial
 */
relay_board *find_board(const char *serial,int debug )
{
	char *respath = NULL;
	int isdevice = 0;
	if (strncmp(serial, "/dev/", 5) == 0) {
		respath = realpath(serial, NULL);

	}

	for (i = 0; i < relay_board_count; i++) {
		if (respath != NULL) {
			if (strcmp(relay_boards[i].path, respath) == 0)
				isdevice = 1;
		}

		if ((strcmp(relay_boards[i].serial, serial) == 0) || (strcmp(relay_boards[i].path, serial) == 0)  || isdevice) {
			if(debug) fprintf(stderr,"find_board(%s) path %s\n",serial,relay_boards[i].path);
			if (respath)
				free(respath);
			return &relay_boards[i];
		}
	}
	if (respath)
		free(respath);
	return NULL;
}

/**
 * Return the count of relay boards
 */
int get_relay_board_count()
{
	return relay_board_count;
}

/** 
 * Return the actual relay_board structs
 */
relay_board *get_relay_boards()
{
	return relay_boards;
}

/**
 * Return all allocated resources and perform any other cleanup
 */
void shutdown()
{

	/* Free static HIDAPI objects. */
	hid_exit();

	for (i = 0; i < relay_board_count; i++) {
		free(relay_boards[i].path);
	}
	if (relay_board_count > 0) {
		free(relay_boards);
	}
}

//Private functions

/**
 * Load the board serial and relay status
 * This intentionally reuses a handle as it's meant to be called by the
 * other functions while they have one already open
 */
static int get_board_features(relay_board * board, hid_device * handle)
{
	unsigned char buf[9] = { 0 };
	//Get the features of the device
	buf[0] = 0x01;
	int ret = hid_get_feature_report(handle, buf, sizeof(buf));
	if (ret == -1) {
		perror("hid_get_feature_report\n");
	}
	if (board->module_type == DCTTECH) {
		//Set the serial number (0x0 for termination)
		memset(board->serial, 0x0, sizeof(board->serial));
		memcpy(board->serial, buf, Serial_Length);

		//Byte 7 in the response contains the target_state of the relays
		board->state = buf[7];
	} else if (board->module_type == UCREATE) {
		return ret;
	}

	return ret;
}

// Function to check if the product is known and return the type
int known_relay(struct hid_device_info *thisdev)
{
	char product[255];
	if (thisdev == NULL)
		return 0;
	sprintf(product, "%ls", thisdev->product_string);
	if (!strncmp(product, "USBRelay", 8))
		return DCTTECH;
	if (!strncmp(product, "HIDRelay", 8))
		return UCREATE;
	return 0;
}