2022-09-04 15:01:35 +02:00
|
|
|
import Vapor
|
|
|
|
import SwiftyGPIO
|
|
|
|
|
2022-09-05 18:16:10 +02:00
|
|
|
var apns: APNSInterface?
|
2022-09-05 18:10:42 +02:00
|
|
|
var tokenStorage: TokenStorage!
|
|
|
|
|
2022-09-04 15:01:35 +02:00
|
|
|
// configures your application
|
|
|
|
public func configure(_ app: Application) throws {
|
|
|
|
|
|
|
|
let resourcesFolderUrl = URL(fileURLWithPath: app.directory.resourcesDirectory)
|
|
|
|
let configUrl = resourcesFolderUrl.appendingPathComponent("config.json")
|
|
|
|
|
2022-09-05 18:10:42 +02:00
|
|
|
tokenStorage = .init(in: resourcesFolderUrl)
|
|
|
|
|
2022-09-04 15:01:35 +02:00
|
|
|
let config: ServerConfiguration
|
|
|
|
do {
|
|
|
|
let data = try Data(contentsOf: configUrl)
|
|
|
|
config = try JSONDecoder().decode(from: data)
|
|
|
|
} catch {
|
2022-09-04 17:09:51 +02:00
|
|
|
print("Failed to load config from \(configUrl.path): \(error)")
|
2022-09-04 15:01:35 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-04 15:40:52 +02:00
|
|
|
app.http.server.configuration.port = config.port
|
|
|
|
|
2022-09-05 18:16:10 +02:00
|
|
|
apns = .init(config)
|
|
|
|
guard apns != nil else {
|
2022-09-04 17:09:51 +02:00
|
|
|
serverStatus = .failedToStart
|
2022-09-04 15:01:35 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
configureGPIO(config)
|
|
|
|
|
|
|
|
// register routes
|
|
|
|
try routes(app)
|
|
|
|
|
|
|
|
serverStatus = .running
|
|
|
|
}
|
|
|
|
|
|
|
|
private extension JSONDecoder {
|
|
|
|
|
|
|
|
func decode<T>(from data: Data) throws -> T where T: Decodable {
|
|
|
|
try self.decode(T.self, from: data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func configureGPIO(_ config: ServerConfiguration) {
|
|
|
|
let gpio = RaspberryGPIO(
|
|
|
|
name: "GPIO\(config.buttonPin)",
|
|
|
|
id: config.buttonPin,
|
|
|
|
baseAddr: 0x7E000000)
|
|
|
|
|
|
|
|
gpio.direction = .IN
|
|
|
|
gpio.pull = .down
|
|
|
|
gpio.bounceTime = config.bounceTime
|
|
|
|
gpio.onChange { _ in
|
|
|
|
log(info: "Push detected")
|
|
|
|
sendPush()
|
|
|
|
}
|
|
|
|
log(info: "GPIO \(config.buttonPin) configured")
|
|
|
|
}
|
|
|
|
|
|
|
|
private func sendPush() {
|
2022-09-05 18:10:42 +02:00
|
|
|
guard !tokenStorage.tokens.isEmpty else {
|
|
|
|
log(info: "No tokens registered to send push")
|
|
|
|
return
|
|
|
|
}
|
2022-09-04 15:01:35 +02:00
|
|
|
Task(priority: .userInitiated) {
|
2022-09-05 18:16:10 +02:00
|
|
|
await apns?.sendPush(to: tokenStorage.tokens)
|
2022-09-04 15:01:35 +02:00
|
|
|
}
|
|
|
|
}
|