在应用程序处于后台状态时运行 Modbus 查询

时间:2021-03-11 14:29:37

标签: ios swift bluetooth background-process modbus

我正在使用 Modbus 协议,在成功设置 TCP 连接后,我能够连接硬件并开始执行连续读取操作,并且在应用程序处于前台时一切正常。

一旦应用程序进入后台状态,我的所有查询就会停止工作。为了验证相同,我添加了日志,但日志也没有在应用程序后台状态显示。

我现在被这个问题困住了,无法确定真正的根本原因。任何人都可以帮助我。以下是我正在使用的代码:

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 个答案:

没有答案
相关问题