====== HTTP request implemention using custom protocol ====== The following example sends a HTTP string template to the TCP port upon the register change in the custom protocol. Once the response comes, is is copied in the //response// global variable which is returned to the system with the **readRegister** function. get_example = [[ GET /api/register-values HTTP/1.1 Host: 127.0.0.1 X-WH-APIKEY:5D78CB6F0B0ACC526F2CB8BF65B471A2E594D309 X-WH-CONNECTIONS: 1 Accept: application/json Content-Type: application/json ]] response = "no data" function createDevices () addDevice({name = "S", shift = 0, base = 10, xtraFields = {}}) end function onScanStart () -- no actions on scan start end function readRegister (reg, device, unitId) return response end function writeRegister (reg, device, unitId, newValue) sendString(get_example .. "\n") local s = read_string() if (not s) or (#s == 0) then return false else response = s -- copy response to global return true end end function read_string() local str = {} repeat local char_ = readString(1) if char_ then -- DEBUG("Read char = " .. char_) table.insert(str, char_) end until not char_ local response = table.concat(str) DEBUG("read_string going to return " .. response) return response end ===== How to change request parameters ===== When you want to dynamically change your request paramters, the above example could be further extended to this verstion: GET_TEMPLATE = { getPath = "GET /api/registers/" , reg = 611, -- can be modified from outside getTail = " HTTP/1.1" .. "\r\n", acceptHeader = "Accept: application/json".."\r\n", -- host = "Host: 192.168.1.110".."\r\n", host = "Host: 127.0.0.1".."\r\n", apiKey = "X-WH-APIKEY: 4025D32205ADC52E8604690FFADFB4600B8D41AA".."\r\n", endLine = "\r\n" } function GET_TEMPLATE : make() local newRequest = self.getPath .. self.reg .. self.getTail .. self.acceptHeader .. self.host .. self.apiKey .. self.endLine return newRequest end function createDevices () addDevice{name = "CMD", shift = 0, base = 10, xtraFields = {} }; end function readRegister (reg, device, unitId) return status_ end function writeRegister (reg, device, unitId, newValue) -- check for zero if (newValue == 0) then status_ = false return true -- no GET will be done else GET_TEMPLATE.reg = newValue -- change target for request end sendString_(GET_TEMPLATE : make() ) local response_ = readAll() if (#response_ > 0) then DEBUG("got something ... " .. response_) status_ = 1 else status_ = false end return true end ------------------ Helpers --------------- -- new sendString version function sendString_(s) DEBUG("Going to send: " .. s) local sendBuf = {} for i = 1, #s do table.insert(sendBuf, s : byte(i) ) end sendBytes(sendBuf) end -- read everything that is in buffer function readAll() local rbuf = {} repeat local b = readString(1) if b then table.insert(rbuf, b) end until (not b) return table.concat(rbuf) end ------------ Not in use ------------------ function onScanStart () end