diff --git a/Sources/IoT-Simulator-Core/IoT_Simulator_Core.swift b/Sources/IoT-Simulator-Core/IoT_Simulator_Core.swift index 96c6d4e..dad3472 100644 --- a/Sources/IoT-Simulator-Core/IoT_Simulator_Core.swift +++ b/Sources/IoT-Simulator-Core/IoT_Simulator_Core.swift @@ -26,7 +26,7 @@ public actor IoTSimulatorCore { // schedule work let task = IoTSimulatorCore.schedule(envID: environment.location, deviceID: device.deviceID) { msg in - print("\(msg.description)\n\n") + //print("\(msg.description)\n\n") } failure: { print("Something is wrong") } @@ -47,6 +47,12 @@ public actor IoTSimulatorCore { return IoTSimulatorCore.devices[devID] } + public static func nukeAll() { + for value in IoTSimulatorCore.dev_tasks { + value.value.cancel() + } + } + private static func schedule( envID: sending String, deviceID: sending String, @@ -55,9 +61,13 @@ public actor IoTSimulatorCore { ) -> Task<(), Never> { return Task { - while true { - let dev = IoTSimulatorCore.getDev(devID: deviceID)! - let env = IoTSimulatorCore.getEnv(name: envID)! + var notCancelled: Bool = true + + let dev = IoTSimulatorCore.getDev(devID: deviceID)! + let env = IoTSimulatorCore.getEnv(name: envID)! + + while notCancelled { + usleep(__useconds_t(dev.dutyCicle * 1000)) let message = dev.work(envrionment: env) do { @@ -65,8 +75,18 @@ public actor IoTSimulatorCore { } catch { failure() } - usleep(__useconds_t(dev.dutyCicle * 1000)) + + do { + try Task.checkCancellation() + } catch { + notCancelled = false + + } + } + + print("Bye, Bye, \(dev.deviceID)\n\n") + } } diff --git a/Tests/IoT-Simulator-CoreTests/IoTCore-Tests.swift b/Tests/IoT-Simulator-CoreTests/IoTCore-Tests.swift index 081a277..8d958a2 100644 --- a/Tests/IoT-Simulator-CoreTests/IoTCore-Tests.swift +++ b/Tests/IoT-Simulator-CoreTests/IoTCore-Tests.swift @@ -63,3 +63,55 @@ import Testing sleep(15) } + +@Test func stressLoop1() async throws { + + let devices: Int = 1000 + + let env = PhysicalEnvironment("Delta") + let truth = PhysicalData(.Temperature, 22) + + env.setPhysicalData(DataType.Temperature, truth) + + IoTSimulatorCore.addEnv(environment: env) + + let signKeyPath = "./Private/privateKey.pem" + + let privateKey = try pem2key(filePath: signKeyPath) + + for i in 0..