Socket connection

I’m having difficulty with a remote socket connection to my UPS server on my local network. Attached is the screenshot of the code I’m using and the response. Can anyone see a problem in how I’m establishing the socket connection.

“Closed” refers to the socket closing unexpectedly. Outside of openLuup, I can remotely connect to the UPS server using a piece of client software called “apcaccess.exe”. Here is the APC manual’s description of how to contact the server:

NIS Network Server Protocol The NIS network server in apcupsd is capable of sending status and events data to clients that request it. The communication between the client and the server is performed over a TCP connection to the NISPORT (normally port 3551). The client opens a connection to the server and sends a message, to which the server will reply with one or more messages. Each message consists of a 2-byte length (in network byte order) followed by that many bytes of data. Both the client->server and server->client messages follow this format. apcupsd supports two commands, sent as the body of a message: 1. "status" - The status command requests that the server send a copy of all status values, in the form displayed by apcaccess. After the client sends the "status" command, the server will reply with a series of messges, each one containing one line of apcaccess status data. The end of the command series is indicated by an empty message (length of 0). 2. "events" - The events command operates the same as "status" except the server replies with lines from the log of recent events. As an example, the following bytes would be sent by a client to solicit the status: 0x00 0x06 0x73 0x74 0x61 0x74 0x75 0x73 The first two bytes are the data length (6) in network byte order. The 6 bytes of data that follow are the ASCII characters for "status". The server will respond to this command with a series of its own messages containing the status data.

The 1st possible problem is that the hex commands are not being sent as hex:

s3 = assert(apc:send("0x00 0x06 0x73 0x74 0x61 0x74 0x75 0x73"))

Need to assemble the string as hex:

s3 = assert(apc:send(string.char(0x00,0x06,0x73,0x74,0x61,0x74,0x75,0x73)))

The socket should be closed before you crash out of the for loop on line 25 or the break on line 22. Subsequent runs of the program may encounter problems. Probably better to use a repeat until loop (or similar) to create just one exit point, that cleans up properly.

local count = 0 local ok = true local done = false

repeat
– do stuff: set ok to false, if an error is deteced
count = count+1
if (count > 100) then ok = false end
until (not OK or done)

– clean up

return OK

That was it! Awesome. I was making a bad assumption that the server would parse the command as hex. Lesson learned.