require("rsmdict")
require("rsm_serials")

--The Objects that is supported by the Script
local obj_ids = {
                   RSM.RSM_TagID.TAG_BUS_SERIAL_DEV                    
                }
      
local devices = {}                
local mdd = {}
local fldd = {}
local ddd = {}

local serial_file = ""
local serial_conf_file_test="/usr/share/lua/kses/test_bus_serial.xml"

local serial_conf_file="/etc/rsm/serialconf.xml"
local mdd_conf_file="/etc/rsm/mddconf.xml"
local fldd_conf_file="/etc/rsm/fldd.conf"
local ddd_conf_file="/etc/rsm/dddconf.xml"
local modbusFiles = {}
local flddFiles = {}
local dddFiles = {}
local modbusPath = ""
local flddPath = ""
local dddPath = ""

local mdd_down = "/usr/bin/sv down mdd"
local mdd_up = "/usr/bin/sv up mdd"

local fldd_down = "/usr/bin/sv down fldd"
local fldd_up = "/usr/bin/sv up fldd"

local ddd_down = "/usr/bin/sv down ddd"
local ddd_up = "/usr/bin/sv up ddd"

function print_table(t,p)

   for k,v in pairs(t) do
     print(p,k,v)
     if(type(v)=="table") then 
         print_table(v,p.."\t")
     end
  end
end


--Retuen the Object List
function getObjects()
 return obj_ids;
end

--Convert the config file into an object message nd return that.
--Actually supposed to check the request object to find the exact object if any to 
--return. We jippo that by always returning all of them
function getConfig(cfg)
  load_serialDev()
  msg = serialDev_to_msg()
  return msg
end


--Function to lookup and set a specific object(s)
--and then to update the cofig file with those values
function setConfig(cfg)
   load_serialDev()   
   update_serialDev(cfg)
   store_serialDev()
end

function deleteConfig(cfg)
   load_serialDev()
   delete_serialDev(cfg)
end

function replaceConfig(cfg)
   
end


function command_exec(cmd)
  local f = io.popen(cmd) 
  value = f:read("*a") or "none"
  f:close()
  return value
end

function scandir(directory)
  local i, t, popen = 0, {}, io.popen
    for filename in popen('ls -a "'..directory..'"'):lines() do
        i = i + 1
        t[i] = filename
    end
    return t
end

function writefile(fileaddres,value)
  local f = io.open(fileaddres,"w+")
  f:write(value)
  f:close()
  return true
end

function load_serialDev() 
  --print("Loading pf data...")   
  sf = command_exec("cat "..serial_conf_file)  
  serial_file = sf  
  devices = {}   
    
  mddConfig = command_exec("cat "..mdd_conf_file)
  flddConfig = command_exec("cat "..fldd_conf_file)
  dddConfig = command_exec("cat "..ddd_conf_file)
  mddFiles = {}
  flddFiles = {}
  dddFiles = {}
  
  if (mddConfig ~= 0) then
    mddPath = mddConfig:match('<path%s+name=%"devices%"%s->(.-)</path>') or ""    
    if (mddPath ~= "") then
      mddFiles = scandir(mddPath)
       --print("Mdd Files:....."..print_table(mddFiles,0))
      table.remove(mddFiles,1)
      table.remove(mddFiles,1)     
    end    
  end
  
  if (flddConfig ~= 0) then
    --flddPath = flddConfig:match([[fldd.device.dir=(.-)%$]]) or ""    
    flddPath = flddConfig:match([[fldd.device.dir=(.-)\n]]) or ""
    flddPath = "/etc/rsm/fldd/devices/"    
    if (flddPath ~= "") then
      flddFiles = scandir(flddPath)
      table.remove(flddFiles,1)
      table.remove(flddFiles,1)
    end    
  end
  
  if (dddConfig ~= 0) then
    dddPath = dddConfig:match('<path%s+name=%"devices%"%s->(.-)</path>') or ""    
    if (dddPath ~= "") then
      dddFiles = scandir(dddPath)
      table.remove(dddFiles,1)
      table.remove(dddFiles,1)
    end    
  end
  
    
  if(mddFiles ~= 0) then
  for idx, mddFile in pairs(mddFiles) do
    cfg = command_exec("cat "..mddPath .. "/" .. mddFile)
    print("Saving mdd file: "..mddFile)
    
    if (cfg:match("<device>(.+)</device>") == nil) then
      print("The following ModBus file is empty: " .. mddFile)
    else
      mdd[mddFile] = {}      
      mdd[mddFile].device = cfg:match([[<port>%s-(.-)%s-</port>]]) or "unknown"
      mdd[mddFile].serialnum = cfg:match([[<serial>%s-(.-)%s-</serial>]]) or "unknown"      
      mdd[mddFile].label = cfg:match([[<label>%s-(.-)%s-</label>]]) or "unknown"
      mdd[mddFile].config = cfg:match([[<config>%s-(.-)%s-</config>]]) or serial_conf_file
      mdd[mddFile].template = cfg:match([[<template>%s-(.-)%s-</template>]]) or "unknown" 
      mdd[mddFile].address = cfg:match([[<slave>%s-(.-)%s-</slave>]]) or "unknown"     
      mdd[mddFile].gateaddress = cfg:match([[<muxslave>%s-(.-)%s-</muxslave>]]) or "unknown"
      mdd[mddFile].muxport = cfg:match([[<muxport>%s-(%d+)%s-</muxport>]]) or "unknown"
      mdd[mddFile].muxbaud = cfg:match([[<muxbaud>%s-(%d+)%s-</muxbaud>]]) or "unknown"      
      mdd[mddFile].muxparity = cfg:match([[<muxparity>%s-(.-)%s-</muxparity>]]) or "unknown"
      mdd[mddFile].muxdata = cfg:match([[<muxdata>%s-(%d+)%s-</muxdata>]]) or "unknown"
      mdd[mddFile].muxstop = cfg:match([[<muxstop>%s-(.-)%s-</muxstop>]]) or "unknown"
      mdd[mddFile].muxtype = cfg:match([[<muxtype>%s-(.-)%s-</muxtype>]]) or "unknown"
      mdd[mddFile].owner = cfg:match([[<owner>%s-(.-)%s-</owner>]]) or "mdd"        
      
      
    end 
  end        
  end 
  
  if(flddFiles ~= 0) then
  for idx, flddFile in pairs(flddFiles) do
    cfg = command_exec("cat "..flddPath .. "/" .. flddFile)
    
    if (cfg:match("<device>(.+)</device>") == nil) then
      print("The following Veeder Root file is empty: " .. flddFile)
    else
      fldd[flddFile] = {}      
      fldd[flddFile].device = cfg:match([[<port>%s-(.-)%s-</port>]]) or "unknown"
      fldd[flddFile].serialnum = cfg:match([[<serial>%s-(.-)%s-</serial>]]) or "unknown"      
      fldd[flddFile].label = cfg:match([[<label>%s-(.-)%s-</label>]]) or "unknown"
      fldd[flddFile].config = cfg:match([[<config>%s-(.-)%s-</config>]]) or serial_conf_file  
      fldd[flddFile].owner = cfg:match([[<owner>%s-(.-)%s-</owner>]]) or "fldd"    
      
    end 
  end        
  end
  
  if(dddFiles ~= 0) then
  for idx, dddFile in pairs(dddFiles) do
    cfg = command_exec("cat "..dddPath .. "/" .. dddFile)
    
    if (cfg:match("<device>(.+)</device>") == nil) then
      print("The following DLMS file is empty: " .. dddFile)
    else
      ddd[dddFile] = {}      
      ddd[dddFile].device = cfg:match([[<port>%s-(.-)%s-</port>]]) or "unknown"
      ddd[dddFile].serialnum = cfg:match([[<serial>%s-(.-)%s-</serial>]]) or "unknown"      
      ddd[dddFile].label = cfg:match([[<label>%s-(.-)%s-</label>]]) or "unknown"
      ddd[dddFile].config = cfg:match([[<config>%s-(.-)%s-</config>]]) or serial_conf_file
      ddd[dddFile].template = cfg:match([[<template>%s-(.-)%s-</template>]]) or "unknown"  
      ddd[dddFile].owner = cfg:match([[<owner>%s-(.-)%s-</owner>]]) or "ddd"       
      
    end         
  end 
  end 
  
  for device, sfConf in (serial_file:gmatch('<port%s+device=%"(.-)%"%s->(.-)</port>')) do
    --deviceCount = deviceCount + 1
    devices[device] = {}
    devices[device].device = device or "unknown"
    devices[device].owner = sfConf:match("<owner>%s-(.-)%s-</owner>") or "" -- type is "owner" in xml      
  end
   
              
end

function serialDev_to_msg()
  local msg = {}
  serial_ctr = 0
  
  --print("Load Message: ")
  
  --ModBus (mdd)
  for idx,mf in pairs(mdd) do     
     serial_cfg = {}
     serial_cfg.objid =  RSM.RSM_TagID.TAG_BUS_SERIAL_DEV
     serial_cfg[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = mf.serialnum
     serial_cfg[RSM.RSM_TagID.TAG_BUS_LABEL] = mf.label
     serial_cfg[RSM.RSM_TagID.TAG_BUS_DEVICE] = mf.device
     serial_cfg[RSM.RSM_TagID.TAG_BUS_PATH] = mf.config
     serial_cfg[RSM.RSM_TagID.TAG_BUS_TEMPLATE] = mf.template
     serial_cfg[RSM.RSM_TagID.TAG_BUS_ADDR] = mf.address
     serial_cfg[RSM.RSM_TagID.TAG_BUS_GATE_ADDR] = mf.gateaddress     
     serial_cfg[RSM.RSM_TagID.TAG_BUS_PORT] = tonumber(mf.muxport)
     serial_cfg[RSM.RSM_TagID.TAG_BUS_BAUD] = tonumber(mf.muxbaud)
     serial_cfg[RSM.RSM_TagID.TAG_BUS_DATA] = tonumber(mf.muxdata)     
     --serial_cfg[RSM.RSM_TagID.TAG_BUS_TYPE] = mf.muxtype  
     
     --print("Ourgoing stop value: "..serial_cfg[RSM.RSM_TagID.TAG_BUS_STOP])   
     
     if (mf.muxstop == "1") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_STOP] = RSM.TAG_BUS_STOP_Types.TAG_BUS_STOP_ONE
     elseif (mf.muxstop == "1.5") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_STOP] = RSM.TAG_BUS_STOP_Types.TAG_BUS_STOP_ONEFIVE
     elseif (mf.muxstop == "2") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_STOP] = RSM.TAG_BUS_STOP_Types.TAG_BUS_STOP_TWO 
     end
     
     if (mf.owner == "rdd") then
        print("Error: Device type does not match!")
     elseif (mf.owner == "mdd") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_OWNER] = RSM.TAG_BUS_OWNER_Types.TAG_BUS_OWNER_MDD 
     elseif (mf.owner == "ddd") then
        print("Error: Device type does not match!")
     elseif (mf.owner == "fldd") then
        print("Error: Device type does not match!")
     elseif (mf.owner == "tsd") then
        print("Error: Device type does not match!")
     end 
     
     if (mf.muxparity == "N") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_PARITY] = RSM.TAG_BUS_PARITY_Types.TAG_BUS_PARITY_NONE
     elseif (mf.muxparity == "E") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_PARITY] = RSM.TAG_BUS_PARITY_Types.TAG_BUS_PARITY_EVEN
     elseif (mf.muxparity == "O") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_PARITY] = RSM.TAG_BUS_PARITY_Types.TAG_BUS_PARITY_ODD 
     elseif (mf.muxparity == "M") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_PARITY] = RSM.TAG_BUS_PARITY_Types.TAG_BUS_PARITY_MARK 
     elseif (mf.muxparity == "S") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_PARITY] = RSM.TAG_BUS_PARITY_Types.TAG_BUS_PARITY_SPACE   
     end   
     
     if (mf.muxtype == "rs232") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_MODE] = RSM.TAG_BUS_MODE_Types.TAG_BUS_MODE_RS232
     elseif (mf.muxparity == "rs485") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_MODE] = RSM.TAG_BUS_MODE_Types.TAG_BUS_MODE_RS485
     elseif (mf.muxparity == "4wire") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_MODE] = RSM.TAG_BUS_MODE_Types.TAG_BUS_MODE_FOURWIRE      
     end      
               
        
     msg[serial_ctr] = serial_cfg
     serial_ctr = serial_ctr+1
  end
  
  --Veeder Root (fldd)
  for idx,flf in pairs(fldd) do 
     serial_cfg = {}
     serial_cfg.objid =  RSM.RSM_TagID.TAG_BUS_SERIAL_DEV         
     serial_cfg[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = flf.serialnum
     serial_cfg[RSM.RSM_TagID.TAG_BUS_LABEL] = flf.label
     serial_cfg[RSM.RSM_TagID.TAG_BUS_DEVICE] = flf.device
     serial_cfg[RSM.RSM_TagID.TAG_BUS_PATH] = flf.config  
     
     if (flf.owner == "rdd") then
        print("Error: Device type does not match!")
     elseif (flf.owner == "mdd") then
        print("Error: Device type does not match!")   
     elseif (flf.owner == "ddd") then
        print("Error: Device type does not match!")  
     elseif (flf.owner == "fldd") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_OWNER] = RSM.TAG_BUS_OWNER_Types.TAG_BUS_OWNER_FLDD 
     elseif (flf.owner == "tsd") then
        print("Error: Device type does not match!")
     end  
             
     msg[serial_ctr] = serial_cfg
     serial_ctr = serial_ctr+1
  end  
  
  --DLMS (ddd)
  for idx,df in pairs(ddd) do 
     serial_cfg = {}
     serial_cfg.objid =  RSM.RSM_TagID.TAG_BUS_SERIAL_DEV         
     serial_cfg[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = df.serialnum
     serial_cfg[RSM.RSM_TagID.TAG_BUS_LABEL] = df.label
     serial_cfg[RSM.RSM_TagID.TAG_BUS_DEVICE] = df.device
     serial_cfg[RSM.RSM_TagID.TAG_BUS_PATH] = df.config 
     serial_cfg[RSM.RSM_TagID.TAG_BUS_TEMPLATE] = df.template 
     
     if (df.owner == "rdd") then
        print("Error: Device type does not match!")
     elseif (df.owner == "mdd") then
        print("Error: Device type does not match!")   
     elseif (df.owner == "ddd") then
        serial_cfg[RSM.RSM_TagID.TAG_BUS_OWNER] = RSM.TAG_BUS_OWNER_Types.TAG_BUS_OWNER_DDD 
     elseif (df.owner == "fldd") then
        print("Error: Device type does not match!") 
     elseif (df.owner == "tsd") then
        print("Error: Device type does not match!")
     end  
             
     msg[serial_ctr] = serial_cfg
     serial_ctr = serial_ctr+1
  end
  
  return msg
end

function update_serialDev(cfg)
   for idx,obj in pairs(cfg) do      
      if obj.objid and obj.objid == RSM.RSM_TagID.TAG_BUS_SERIAL_DEV then                    
          if obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] ~= '' then
              print("Incoming Serial nunmber: "..obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM])        
              --obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] .. ".xml"  
              
               for idx,mf in pairs(mdd) do
                  if mf.serialnum == obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] then
                      obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] .. ".xml"  
                      sf = mdd[obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM]]
                      print("Identified ModBus")
                      if sf then
                          setserialDev(sf,obj)
                      end
                  else
                      print("Error: Serial number not a match!")
                  end
               end
               for idx,df in pairs(ddd) do
                  if df.serialnum == obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] then
                      obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] .. ".xml"  
                      sf = ddd[obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM]]
                      print("Identified DLMS")
                      if sf then
                          setserialDev(sf,obj)
                      end
                  else
                      print("Error: Serial number not a match!")
                  end
               end
               for idx,flf in pairs(fldd) do
                  if flf.serialnum == obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] then
                      obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] .. ".xml"  
                      sf = fldd[obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM]]
                      print("Identified Veeder Root")
                      if sf then
                          setserialDev(sf,obj)
                      end
                  else
                      print("Error: Serial number not a match!")
                  end
               end              
                                           
              --print("Adding object: " .. obj[RSM.RSM_TagID.TAG_NET_LABEL]);
              --[[if sf then
                setserialDev(sf,obj)
              end]]--
          else--New serial devices
              print("Recognised new device...") 
              --Generate new serial number            
              newSerialnum = generateNewSerial()              
              newFile = newSerialnum..".xml" 
              
              print("Incomming device name: "..obj[RSM.RSM_TagID.TAG_BUS_DEVICE])                      
                            
              for idx,tf in pairs(devices) do
                  --Check if the serial bus exists
                  print("Checking device name: "..tf.device)
                  if obj[RSM.RSM_TagID.TAG_BUS_DEVICE] == tf.device then
                      print("Identified Device: "..tf.device) 
                      --Check device type and set                     
                      if tf.owner == "mdd" then
                          mdd[newFile] = {}
                          sf = mdd[newFile]
                          sf.owner = "mdd"
                          if sf then
                              sf.serialnum = newSerialnum 
                              sf.device = obj[RSM.RSM_TagID.TAG_BUS_DEVICE]
                              sf.config = serial_conf_file                
                              setserialDev(sf,obj)
                          end
                      elseif tf.owner == "ddd" then
                          ddd[newFile] = {}
                          sf = ddd[newFile]
                          sf.owner = "ddd"
                          if sf then
                              sf.serialnum = newSerialnum 
                              sf.device = obj[RSM.RSM_TagID.TAG_BUS_DEVICE]
                              sf.config = serial_conf_file                
                              setserialDev(sf,obj)
                          end
                      elseif tf.owner == "fldd" then
                          fldd[newFile] = {}
                          sf = fldd[newFile]
                          sf.owner = "fldd"
                          if sf then
                              sf.serialnum = newSerialnum 
                              sf.device = obj[RSM.RSM_TagID.TAG_BUS_DEVICE]
                              sf.config = serial_conf_file                
                              setserialDev(sf,obj)
                          end
                      else
                          print("Error: Not a valid device!")
                      end                    
                                   
                  else
                      print("Error: Device bus does not exist!")
                  end
                end              
              
               
              --[[if sf then
                sf.serialnum = newSerialnum 
                sf.device = obj[RSM.RSM_TagID.TAG_BUS_DEVICE]
                sf.config = serial_conf_file                  
                                                           
                setserialDev(sf,obj)
              end]]--
              
          end -- if serial       
          
      end -- if   
   end -- for
end --function


function setserialDev(sf,obj)
    
    if obj[RSM.RSM_TagID.TAG_BUS_LABEL] then
       sf.label = obj[RSM.RSM_TagID.TAG_BUS_LABEL]
    end
    
  if sf.owner ~= "fldd" then 

    if obj[RSM.RSM_TagID.TAG_BUS_TEMPLATE] then
       sf.template = obj[RSM.RSM_TagID.TAG_BUS_TEMPLATE]
    end
  end

  if sf.owner == "mdd" then
    
    if obj[RSM.RSM_TagID.TAG_BUS_ADDR] then
       sf.address = obj[RSM.RSM_TagID.TAG_BUS_ADDR]
    end
    
    if obj[RSM.RSM_TagID.TAG_BUS_GATE_ADDR] then
       sf.gateaddress = obj[RSM.RSM_TagID.TAG_BUS_GATE_ADDR]
    end
    
    if obj[RSM.RSM_TagID.TAG_BUS_PORT] then
       sf.muxport = obj[RSM.RSM_TagID.TAG_BUS_PORT]
    end
    
    if obj[RSM.RSM_TagID.TAG_BUS_BAUD] then
    
        if obj[RSM.RSM_TagID.TAG_BUS_BAUD] == 49664 then
          sf.muxbaud = 115200
        else
          sf.muxbaud = obj[RSM.RSM_TagID.TAG_BUS_BAUD]
        end
    end
    
    if obj[RSM.RSM_TagID.TAG_BUS_DATA] then
       sf.muxdata = obj[RSM.RSM_TagID.TAG_BUS_DATA]
    end
        
    
    if obj[RSM.RSM_TagID.TAG_BUS_STOP] then    
       if obj[RSM.RSM_TagID.TAG_BUS_STOP] == RSM.TAG_BUS_STOP_Types.TAG_BUS_STOP_ONE then  
          sf.muxstop = "1"
       end 
       if obj[RSM.RSM_TagID.TAG_BUS_STOP] == RSM.TAG_BUS_STOP_Types.TAG_BUS_STOP_ONEFIVE then  
          sf.muxstop = "1.5"
       end 
       if obj[RSM.RSM_TagID.TAG_BUS_STOP] == RSM.TAG_BUS_STOP_Types.TAG_BUS_STOP_TWO then  
          sf.muxstop = "2"
       end        
    end
    
    if obj[RSM.RSM_TagID.TAG_BUS_PARITY] then    
       if obj[RSM.RSM_TagID.TAG_BUS_PARITY] == RSM.TAG_BUS_PARITY_Types.TAG_BUS_PARITY_NONE then  
          sf.muxparity = "N"
       end 
       if obj[RSM.RSM_TagID.TAG_BUS_PARITY] == RSM.TAG_BUS_PARITY_Types.TAG_BUS_PARITY_EVEN then  
          sf.muxparity = "E"
       end 
       if obj[RSM.RSM_TagID.TAG_BUS_PARITY] == RSM.TAG_BUS_PARITY_Types.TAG_BUS_PARITY_ODD then  
          sf.muxparity = "O"
       end 
       if obj[RSM.RSM_TagID.TAG_BUS_PARITY] == RSM.TAG_BUS_PARITY_Types.TAG_BUS_PARITY_MARK then  
          sf.muxparity = "M"
       end  
       if obj[RSM.RSM_TagID.TAG_BUS_PARITY] == RSM.TAG_BUS_PARITY_Types.TAG_BUS_PARITY_SPACE then  
          sf.muxparity = "S"
       end 
    end
    
    if obj[RSM.RSM_TagID.TAG_BUS_MODE] then    
       if obj[RSM.RSM_TagID.TAG_BUS_MODE] == RSM.TAG_BUS_MODE_Types.TAG_BUS_MODE_RS232 then  
          sf.muxtype = "rs232"
       end 
       if obj[RSM.RSM_TagID.TAG_BUS_MODE] == RSM.TAG_BUS_MODE_Types.TAG_BUS_MODE_RS485 then  
          sf.muxtype = "rs485"
       end   
       if obj[RSM.RSM_TagID.TAG_BUS_MODE] == RSM.TAG_BUS_MODE_Types.TAG_BUS_MODE_FOURWIRE then  
          sf.muxtype = "4wire"
       end
    end    
  end
     
    sf.changed = 1
    print("Device-Changed status: " ..sf.changed)
end

function store_serialDev()

--ModBus (mdd)
  for idx,mf in pairs(mdd) do
         if mf.changed and mf.changed == 1 then
            newXML_mdd = [[
<!-- ]]..mddPath..[[/]]..mf.serialnum..[[.xml generated by webconfig -->
<device>
    <label>]]..mf.label..[[</label>
    <serial>]]..mf.serialnum..[[</serial>
    <template>]]..mf.template..[[</template>
    <serialport>
        <config>]]..mf.config..[[</config>
        <port>]]..mf.device..[[</port>
        <owner>]]..mf.owner..[[</owner>
        <slave>]]..mf.address..[[</slave>
        <muxport>]]..mf.muxport..[[</muxport>
        <muxslave>]]..mf.gateaddress..[[</muxslave>
        <muxbaud>]]..mf.muxbaud..[[</muxbaud>
        <muxparity>]]..mf.muxparity..[[</muxparity>
        <muxdata>]]..mf.muxdata..[[</muxdata>
        <muxstop>]]..mf.muxstop..[[</muxstop>
        <muxtype>]]..mf.muxtype..[[</muxtype>
    </serialport>    
</device>
<!-- end of file -->
]]

            command_exec(mdd_down)
            writefile(mddPath..[[/]]..mf.serialnum..[[.xml]],newXML_mdd)
            command_exec(mdd_up)
         end       
  end 

--DLMS (ddd)  
  for idx,df in pairs(ddd) do
         if df.changed and df.changed == 1 then
            newXML_ddd = [[
<!-- ]]..dddPath..[[/]]..df.serialnum..[[.xml generated by webconfig -->
<device>
    <label>]]..df.label..[[</label>
    <serial>]]..df.serialnum..[[</serial>
    <template>]]..df.template..[[</template>
    <serialport>
        <config>]]..df.config..[[</config>
        <port>]]..df.device..[[</port>
        <owner>]]..df.owner..[[</owner>        
    </serialport>    
</device>
<!-- end of file -->
]]

            command_exec(ddd_down)
            writefile(dddPath..[[/]]..df.serialnum..[[.xml]],newXML_ddd)
            command_exec(ddd_up)
         end       
  end  
  
  --Veeder Root (fldd)  
  for idx,flf in pairs(fldd) do
         if flf.changed and flf.changed == 1 then
            newXML_fldd = [[
<!-- ]]..flddPath..[[/]]..flf.serialnum..[[.xml generated by webconfig -->
<device>
    <label>]]..flf.label..[[</label>
    <serial>]]..flf.serialnum..[[</serial>    
    <serialport>
        <config>]]..flf.config..[[</config>
        <port>]]..flf.device..[[</port>
        <owner>]]..flf.owner..[[</owner>        
    </serialport>  
    <samplerate>1</samplerate>  
</device>
<!-- end of file -->
]]

            command_exec(fldd_down)
            writefile(flddPath..[[/]]..flf.serialnum..[[.xml]],newXML_fldd)
            command_exec(fldd_up)
         end       
  end  
  
end

function delete_serialDev(cfg)

    for idx,obj in pairs(cfg) do      
      if obj.objid and obj.objid == RSM.RSM_TagID.TAG_BUS_SERIAL_DEV then                    
          if obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] ~= '' then
              print("Deleting serial number: "..obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM])                      
              
               for idx,mf in pairs(mdd) do
                  if mf.serialnum == obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] then
                      obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] .. ".xml"  
                      sf = mdd[obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM]]
                      print("Identified ModBus")
                      if sf then
                          sf.owner = "mdd"
                          delserialDev(sf,obj)
                      end
                  else
                      print("Error: Serial number not a match!")
                  end
               end
               for idx,df in pairs(ddd) do
                  if df.serialnum == obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] then
                      obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] .. ".xml"  
                      sf = ddd[obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM]]
                      print("Identified DLMS")
                      if sf then
                          sf.owner = "ddd"
                          delserialDev(sf,obj)
                      end
                  else
                      print("Error: Serial number not a match!")
                  end
               end
               for idx,flf in pairs(fldd) do
                  if flf.serialnum == obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] then
                      obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] .. ".xml"  
                      sf = fldd[obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM]]
                      print("Identified Veeder Root")
                      if sf then
                          sf.owner = "fldd"
                          delserialDev(sf,obj)
                      end
                  else
                      print("Error: Serial number not a match!")
                  end
               end              
                                           
              
          else--New serial devices
              print("Error: No serial nmber provided to delete!")
          end -- if serial       
          
      end -- if   
   end -- for
    
end

function delserialDev(sf,obj)
    
    if sf.owner == "mdd" then
        print("Deleting modbus device: "..sf.serialnum)
        command_exec(mdd_down)
        command_exec("rm "..mddPath..[[/]]..sf.serialnum..[[.xml]])
        command_exec(mdd_up)
    elseif sf.owner == "ddd" then
        print("Deleting DLMS device: "..sf.serialnum)
        command_exec(ddd_down)
        command_exec("rm "..dddPath..[[/]]..sf.serialnum..[[.xml]])
        command_exec(ddd_up)
    elseif sf.owner == "fldd" then
        print("Deleting Veeder Root device: "..sf.serialnum)
        command_exec(fldd_down)
        command_exec("rm "..flddPath..[[/]]..sf.serialnum..[[.xml]])
        command_exec(fldd_up)
    else
        print("Error: Unable to delete device")
    end
end

--Testing....

--print("Testing...")
--print("Get Config: ")

--print_table(getConfig(),0)

--[[local testCfg = {}
local delCfg = {}
local obj ={}
local obj1 ={}
local obj2 ={}
local obj3 ={}


obj.objid = RSM.RSM_TagID.TAG_BUS_SERIAL_DEV
obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = "0x7FA41A18"
--obj[RSM.RSM_TagID.TAG_BUS_DEVICE] = "/dev/ttyS1"
--obj[RSM.RSM_TagID.TAG_BUS_LABEL] = "TEST"     
--obj[RSM.RSM_TagID.TAG_BUS_TEMPLATE] = "t2s.xml"
--obj[RSM.RSM_TagID.TAG_BUS_ADDR] = "1.2.3.55"
--obj[RSM.RSM_TagID.TAG_BUS_GATE_ADDR] = "1.2.3.44"
--obj[RSM.RSM_TagID.TAG_BUS_PORT] = 88
--obj[RSM.RSM_TagID.TAG_BUS_BAUD] = "115200"
--obj[RSM.RSM_TagID.TAG_BUS_PARITY] = 1
--obj[RSM.RSM_TagID.TAG_BUS_DATA] = 5
obj[RSM.RSM_TagID.TAG_BUS_STOP] = "1.1"
--obj[RSM.RSM_TagID.TAG_BUS_MODE] = 1

obj1.objid = RSM.RSM_TagID.TAG_BUS_SERIAL_DEV
obj1[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = ""
obj1[RSM.RSM_TagID.TAG_BUS_DEVICE] = "/dev/ttyS1"
obj1[RSM.RSM_TagID.TAG_BUS_LABEL] = "TESTdlms"     
obj1[RSM.RSM_TagID.TAG_BUS_TEMPLATE] = "LandisAndGyr.xml"

obj2.objid = RSM.RSM_TagID.TAG_BUS_SERIAL_DEV
obj2[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = "123"
obj2[RSM.RSM_TagID.TAG_BUS_DEVICE] = "/dev/ttyS1"
obj2[RSM.RSM_TagID.TAG_BUS_LABEL] = "TESTfldd"    

obj3.objid = RSM.RSM_TagID.TAG_BUS_SERIAL_DEV
obj3[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = "0x7FA41A28"    

testCfg[0] = obj
--testCfg[1] = obj1

delCfg[0] = obj3


--setConfig(testCfg)
deleteConfig(delCfg)]]--




























