Contenidos
Servidor en Kotlin
Importar librerías
1 2 3 4 |
io.ktor:ktor-server-netty:1.6.7 io.ktor:ktor-gson:1.6.7 org.slf4j:slf4j-simple:2.0.0-alpha1 org.slf4j:slf4j-simple:1.7.32 |
Código del servidor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import io.ktor.application.* import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.request.receiveText import io.ktor.response.respond import io.ktor.routing.post import io.ktor.routing.routing import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty fun main() { val server = embeddedServer(Netty, port = 6000) { routing { post("/send-message") { val receivedMessage = call.receiveText() println("Mensaje recibido: $receivedMessage") call.respond(HttpStatusCode.OK, "Mensaje recibido: $receivedMessage") } } } server.start(wait = true) } |
Cliente en Swift para el Apple Watch que envía la frecuencia cardiaca
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
import SwiftUI import HealthKit class HeartRateManager: ObservableObject { let healthStore = HKHealthStore() @Published var heartRate: Double = 0.0 var query: HKObserverQuery? var isMonitoring = false func startHeartRateMonitoring() { guard HKHealthStore.isHealthDataAvailable() else { print("HealthKit no está disponible en este dispositivo") return } let readTypes: Set<HKObjectType> = [HKObjectType.quantityType(forIdentifier: .heartRate)!] healthStore.requestAuthorization(toShare: nil, read: readTypes) { [weak self] (success, error) in guard let self = self, success else { print("No se pudo obtener acceso a los datos de frecuencia cardíaca: \(error?.localizedDescription ?? "")") return } let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate)! self.query = HKObserverQuery(sampleType: heartRateType, predicate: nil) { [weak self] (query, completionHandler, error) in guard let self = self, self.isMonitoring else { return } let query = HKSampleQuery(sampleType: heartRateType, predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { (query, results, error) in if let samples = results as? [HKQuantitySample] { if let latestSample = samples.last { let pulse = latestSample.quantity.doubleValue(for: HKUnit.count().unitDivided(by: .minute())) DispatchQueue.main.async { self.heartRate = pulse self.sendMessage(pulse) // Envía el valor de la frecuencia cardíaca } } } } self.healthStore.execute(query) completionHandler() } self.healthStore.execute(self.query!) self.isMonitoring = true } } func stopHeartRateMonitoring() { self.isMonitoring = false if let query = query { healthStore.stop(query) } } func sendMessage(_ heartRateValue: Double) { let messageToSend = "\(heartRateValue)" if let url = URL(string: "http://192.168.1.55:6000/send-message") { var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/text", forHTTPHeaderField: "Content-Type") // Establece el tipo de contenido let data = messageToSend.data(using: .utf8) // Convierte el mensaje a datos request.httpBody = data let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error: \(error.localizedDescription)") } else if let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) { print("Mensaje enviado con éxito") } else { print("Error al enviar el mensaje") } } task.resume() } else { print("URL no válida") } } } struct ContentView: View { @StateObject var heartRateManager = HeartRateManager() var body: some View { VStack { Text("Frecuencia Cardíaca: \(heartRateManager.heartRate)") .padding() Button(action: { heartRateManager.startHeartRateMonitoring() }) { Text("Iniciar Medición") .padding() .foregroundColor(.white) .background(Color.blue) .cornerRadius(8) } } .onDisappear { heartRateManager.stopHeartRateMonitoring() } } } @main struct WatchApp: App { var body: some Scene { WindowGroup { ContentView() } } } |