Run Modbus Queries while the app is in background state

Viewed 77

I'm working with Modbus protocol and after successfully setup TCP connection, I am able to connect with the hardware and start performing continuous reading operations and everything working fine while the application is in foreground.

As soon as the application moves to background state, all my queries stop working. To verify the same, I added logs but logs were also not showing in application background state.

I am stuck with this issue now and not able to identify the actual root cause. Can anyone help me in this. Below is the code which I'm using:

class DemoFile: NSObject {

var mb: OpaquePointer?
var modbusQueue: DispatchQueue?
var ipAddress: NSString?

init(ipAddress: NSString, port: Int32, device: Int32) {
    super.init()
    modbusQueue = DispatchQueue(label: "com.iModbus.modbusQueue")
    let _ = self.setupTCP(ipAddress: ipAddress, port: port, device: device)
}

func setupTCP(ipAddress: NSString, port: Int32, device: Int32) -> Bool {
    self.ipAddress = ipAddress
    mb = modbus_new_tcp(ipAddress.cString(using: String.Encoding.ascii.rawValue) , port)
    var modbusErrorRecoveryMode = modbus_error_recovery_mode(0)
    modbusErrorRecoveryMode = modbus_error_recovery_mode(rawValue: MODBUS_ERROR_RECOVERY_LINK.rawValue | MODBUS_ERROR_RECOVERY_PROTOCOL.rawValue)
    modbus_set_error_recovery(mb!, modbusErrorRecoveryMode)
    modbus_set_slave(mb!, device)
    return true
}

private func buildNSError(errno: Int32, errorString: NSString) -> NSError {
    var details: [String: Any] = [:]
    details[NSLocalizedDescriptionKey] = errorString
    let error = NSError(domain: "Modbus", code: Int(errno), userInfo: details)
    return error
}

private func buildNSError(errno: Int32) -> NSError {
    let errorString = NSString(utf8String: modbus_strerror(errno))
    return self.buildNSError(errno: errno, errorString: errorString!)
}

//Step 1 First I make a connection with my modbus RTU
/**
 Function to establish modbus TCP connection with success and error handled
 */
func connect(success: @escaping () -> Void, failure: @escaping (NSError) -> Void) {
    modbusQueue?.async {
        let ret = modbus_connect(self.mb!)
        if ret == -1 {
            let error = self.buildNSError(errno: errno)
            DispatchQueue.main.async {
                failure(error)
            }
        }
        else {
            DispatchQueue.main.async {
                success()
            }
        }
    }
}
//Step 2 I start perform read operations with my connected Modbus RTU
/**
 Function to read register from the start of the address and till (according to the count)
 
 - parameter startaddress: the address of the starting register
 
 - parameter count: the number of consecutive registers to be read
 
 */
func readRegistersFrom(startAddress: Int32, count: Int32, success: @escaping ([AnyObject]) -> Void, failure: @escaping (NSError) -> Void) {
    modbusQueue?.async {
        let tab_reg: UnsafeMutablePointer<UInt16> = UnsafeMutablePointer<UInt16>.allocate(capacity: Int(count))
        if modbus_read_registers(self.mb!, startAddress, count, tab_reg) >= 0 {
            let returnArray: NSMutableArray = NSMutableArray(capacity: Int(count))
            for i in 0..<Int(count) {
                returnArray.add(Int(tab_reg[i]))
            }
            DispatchQueue.main.async {
                success(returnArray as [AnyObject])
            }
        }
        else {
            let error = self.buildNSError(errno: errno)
            DispatchQueue.main.async {
                failure(error)
            }
        }
    }
}
//Step 3 It will gives me response
//Step 4 With the help of for Loop I am continue reading the values
////Calling the readInput Function for getting continue response
func readModbusData() {
    for _ in 0..<2000 {
        self.readRegistersFrom(startAddress: 51, count: 1) { (result) in
            print("Success: \(result)")
        } failure: { (error) in
            print("Error: \(error.localizedDescription)")
        }
    }
}
/*
 Problem Statement: When my app goes to active state to background state It's stop the execution of modbus query and also, I am not able to print my communication logs also
 */

}

0 Answers
Related