int upsdrv_initups(void) { upsfd = ser_open(device_path); ser_set_speed(upsfd, device_path, B9600); /*get the UPS in the right frame of mind*/ ser_send_pace(upsfd, 100, "%s", COMMAND_END); ser_send_pace(upsfd, 100, "%s", COMMAND_END); sleep (1); return 1; }
/* returns < 0 on errors, 0 on timeout and > 0 on success. */ static int upscsend(const char *cmd) { int res; res = ser_send_pace(upsfd, output_pace_usec, "%s%s%s", use_pre_lf ? "\n" : "", cmd, use_crlf ? "\r\n" : "\r"); if (res < 0) { upsdebug_with_errno(3, "upscsend"); } else if (res == 0) { upsdebugx(3, "upscsend: Timeout"); } else { upsdebugx(3, "upscsend: '%s'", cmd); } return res; }
static int do_command(char type, const char *command, const char *parameters, char *response) { char buffer[SMALLBUF]; int count, ret; ser_flush_io(upsfd); if (response) { *response = '\0'; } snprintf(buffer, sizeof(buffer), "~00%c%03d%s%s", type, (int)(strlen(command) + strlen(parameters)), command, parameters); ret = ser_send_pace(upsfd, 10000, "%s", buffer); if (ret <= 0) { upsdebug_with_errno(3, "do_command: send [%s]", buffer); return -1; } upsdebugx(3, "do_command: %d bytes sent [%s] -> OK", ret, buffer); ret = ser_get_buf_len(upsfd, (unsigned char *)buffer, 4, 3, 0); if (ret < 0) { upsdebug_with_errno(3, "do_command: read"); return -1; } if (ret == 0) { upsdebugx(3, "do_command: read -> TIMEOUT"); return -1; } buffer[ret] = '\0'; upsdebugx(3, "do_command: %d byted read [%s]", ret, buffer); if (!strcmp(buffer, "~00D")) { ret = ser_get_buf_len(upsfd, (unsigned char *)buffer, 3, 3, 0); if (ret < 0) { upsdebug_with_errno(3, "do_command: read"); return -1; } if (ret == 0) { upsdebugx(3, "do_command: read -> TIMEOUT"); return -1; } buffer[ret] = '\0'; upsdebugx(3, "do_command: %d bytes read [%s]", ret, buffer); count = atoi(buffer); if (count >= MAX_RESPONSE_LENGTH) { upsdebugx(3, "do_command: response exceeds expected size!"); return -1; } if (count && !response) { upsdebugx(3, "do_command: response not expected!"); return -1; } if (count == 0) { return 0; } ret = ser_get_buf_len(upsfd, (unsigned char *)response, count, 3, 0); if (ret < 0) { upsdebug_with_errno(3, "do_command: read"); return -1; } if (ret == 0) { upsdebugx(3, "do_command: read -> TIMEOUT"); return -1; } response[ret] = '\0'; upsdebugx(3, "do_command: %d bytes read [%s]", ret, response); /* Tripp Lite pads their string responses with spaces. I don't like that, so I remove them. This is safe to do with all responses for this protocol, so I just do that here. */ rtrim(response, ' '); return ret; } if (!strcmp(buffer, "~00A")) { return 0; } return -1; }