Skip to content

Commit

Permalink
Added feature for 10 minute refresh time on macOS
Browse files Browse the repository at this point in the history
  • Loading branch information
DarraghRogan committed Aug 28, 2021
1 parent 290dbdc commit fbdd498
Show file tree
Hide file tree
Showing 12 changed files with 194 additions and 145 deletions.
2 changes: 1 addition & 1 deletion Miasma iOS/ContentViewSmartCitizen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public struct ContentViewSmartCitizen: View {
.font(.headline)

HStack {
ProgressView("☁️ \(smartCitizenData.data?.sensors?[8].value ?? 0) PM2.5", value: Float16(smartCitizenData.data?.sensors?[8].value ?? 0), total: 500)
ProgressView("☁️ \(String(smartCitizenViewModel.sensors[8].value ?? 0))PM2.5", value: Float16(smartCitizenViewModel.Welcome.sensors[8].value ?? 0.0), total: 500)
.progressViewStyle(aQIProgressBarStyle())
.padding(.top, 0.5)
.padding(.bottom, 7.0)
Expand Down
3 changes: 2 additions & 1 deletion Miasma iOS/DataLoaderPurpleAir.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ extension PurpleAirViewModel {
receiveValue: {
self.purpleAirdata = $0.purpleAirdata
})
print(purpleAirdata)
}
}

Expand All @@ -62,7 +63,7 @@ struct PurpleAirAPIClient {
.tryMap { result -> Response<T> in
let value = try JSONDecoder().decode(
T.self, from: result.data)
// print(Response<Any>.self)
print(Response<Any>.self)
return Response(value: value, response: result.response)
}
.receive(on: DispatchQueue.main)
Expand Down
100 changes: 53 additions & 47 deletions Miasma iOS/DataLoaderSmartCitizen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@ import Foundation
import Combine

struct SmartCitizenResponse: Codable {
let smartCitizendata: SmartCitizenDataClass
let smartCitizendata: Welcome

enum CodingKeys: String, CodingKey {
case smartCitizendata = "data"
}
// enum CodingKeys: String, CodingKey {
// case smartCitizendata = "/"
// }
}



class SmartCitizenViewModel: ObservableObject {

@Published var smartCitizendata: SmartCitizenDataClass = SmartCitizenDataClass()
@Published var smartCitizendata: Welcome = Welcome()

var smartCitizenCancellationToken: AnyCancellable?

Expand All @@ -35,7 +35,7 @@ class SmartCitizenViewModel: ObservableObject {
extension SmartCitizenViewModel {

func getSmartCitizen() {
smartCitizenCancellationToken = SmartCitizenDB.request(.city)
smartCitizenCancellationToken = SmartCitizenDB.request(.station)
.mapError({ (error) -> Error in
print(error)
return error
Expand All @@ -44,7 +44,7 @@ extension SmartCitizenViewModel {
receiveValue: {
self.smartCitizendata = $0.smartCitizendata
})
print(ProfileEditor().SensorID)
// print(ProfileEditor().SensorID)
print(smartCitizendata)
}
}
Expand All @@ -63,12 +63,17 @@ struct SmartCitizenAPIClient {
.tryMap { result -> Response<T> in
let value = try JSONDecoder().decode(
T.self, from: result.data)

// print(Response<Any>.self)
print(result.response)

return Response(value: value, response: result.response)

}
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()


}
}

Expand All @@ -78,7 +83,7 @@ enum SmartCitizenDB {
}

enum SmartCitizenAPIPath: String {
case city = "/"
case station = ""
}

extension SmartCitizenDB {
Expand All @@ -87,7 +92,7 @@ extension SmartCitizenDB {

guard var components = URLComponents(url: baseUrl.appendingPathComponent(path.rawValue), resolvingAgainstBaseURL: true)
else { fatalError("Couldn't create URL Components")}
components.queryItems = [URLQueryItem(name: "token", value: APIKeyWAQI)]
// components.queryItems = [URLQueryItem(name: "token", value: APIKeyWAQI)]

let request = URLRequest(url: components.url!)

Expand All @@ -97,6 +102,7 @@ extension SmartCitizenDB {

.map(\.value)
.eraseToAnyPublisher()

}
}
// define the strucutre of the JSON that will be decoded - came from https://app.quicktype.io
Expand All @@ -112,7 +118,7 @@ struct SmartCitizenDataStructure: Codable {
// var lastReadingAt, addedAt, updatedAt: Date?
// var macAddress: String?
var owner: Owner?
var data: SmartCitizenDataClass?
var data: Welcome?
// var kit: Kit?

enum CodingKeys: String, CodingKey {
Expand All @@ -137,7 +143,7 @@ struct SmartCitizenDataStructure: Codable {
}

// MARK: - DataClass
struct SmartCitizenDataClass: Codable {
struct Welcome: Codable {
// var recordedAt, addedAt: Date?
var location: DataLocation?
var sensors: [SmartCitizenSensor]?
Expand Down Expand Up @@ -512,46 +518,46 @@ class JSONAny: Codable {
// define an instance of the data that can be filled by the data loader and read by the menu
var smartCitizenData = SmartCitizenDataStructure()

public class DataLoaderSmartCitizen {
func loadSmartCitizenData(id:String) {
let request = NSMutableURLRequest(url: NSURL(string:
"https://api.smartcitizen.me/v0/devices/\(id)")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
//public class DataLoaderSmartCitizen {
//
//
// func loadSmartCitizenData(id:String) {
//
// let request = NSMutableURLRequest(url: NSURL(string:
// "https://api.smartcitizen.me/v0/devices/\(id)")! as URL,
// cachePolicy: .useProtocolCachePolicy,
// timeoutInterval: 10.0)
//
//
// request.httpMethod = "GET"
//
// let session = URLSession.shared
// let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
// if (error != nil) {
// print(error)
// } else {
// let httpResponse = response as? HTTPURLResponse
// print("Received from the SmartCitizen API")
// if let data = data,
// let urlContent = NSString(data: data, encoding: String.Encoding.ascii.rawValue) {
// print(urlContent)
// } else {
// print("error with printing string encoded data")
// }
//Parse JSON
let decoder = JSONDecoder()
do {
let dataFromSmartCitizen = try decoder.decode(SmartCitizenDataStructure.self, from: data!)
smartCitizenData = dataFromSmartCitizen
}
catch {
print("Error in SmartCitizen JSON parsing")
// print(purpleAirData)
}
}
})
dataTask.resume()
}
}
// //Parse JSON
// let decoder = JSONDecoder()
// do {
// let dataFromSmartCitizen = try decoder.decode(SmartCitizenDataStructure.self, from: data!)
// smartCitizenData = dataFromSmartCitizen
//
// }
// catch {
// print("Error in SmartCitizen JSON parsing")
// // print(purpleAirData)
// }
// }
// })
//
// dataTask.resume()
// }
//}
8 changes: 4 additions & 4 deletions Miasma.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -987,7 +987,7 @@
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 28;
CURRENT_PROJECT_VERSION = 29;
DEVELOPMENT_TEAM = VDLCQ62KZH;
ENABLE_HARDENED_RUNTIME = YES;
EXCLUDED_ARCHS = "";
Expand All @@ -997,7 +997,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 10.12;
MARKETING_VERSION = 1.20;
MARKETING_VERSION = 1.21;
PRODUCT_BUNDLE_IDENTIFIER = "Darragh-Rogan.Miasma";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
Expand All @@ -1013,7 +1013,7 @@
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 28;
CURRENT_PROJECT_VERSION = 29;
DEVELOPMENT_TEAM = VDLCQ62KZH;
ENABLE_HARDENED_RUNTIME = YES;
EXCLUDED_ARCHS = "";
Expand All @@ -1023,7 +1023,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 10.12;
MARKETING_VERSION = 1.20;
MARKETING_VERSION = 1.21;
PRODUCT_BUNDLE_IDENTIFIER = "Darragh-Rogan.Miasma";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@
endingColumnNumber = "9223372036854775807"
startingLineNumber = "88"
endingLineNumber = "88"
landmarkName = "unknown"
landmarkType = "0">
landmarkName = "loadClimaCellData(lat:lon:)"
landmarkType = "7">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
Expand All @@ -80,8 +80,8 @@
endingColumnNumber = "9223372036854775807"
startingLineNumber = "90"
endingLineNumber = "90"
landmarkName = "unknown"
landmarkType = "0">
landmarkName = "loadClimaCellData(lat:lon:)"
landmarkType = "7">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
<key>Miasma WidgetExtension.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>9</integer>
<integer>8</integer>
</dict>
<key>Miasma iOS.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>8</integer>
<integer>10</integer>
</dict>
<key>Miasma.xcscheme_^#shared#^_</key>
<dict>
Expand All @@ -24,7 +24,7 @@
<key>MiasmaLauncher.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>10</integer>
<integer>9</integer>
</dict>
<key>MiasmaLauncherApplication.xcscheme_^#shared#^_</key>
<dict>
Expand Down
19 changes: 14 additions & 5 deletions Miasma/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,19 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele
defaults.set(50, forKey:"ClimbingAQINotificationsTrigger")
defaults.set("🟢", forKey: "PreviousStateForNotification")

// this is where most returning users should end up and they need an initial state for the notifications

// this is where users should end up and allows population of the RefreshInterval feature introduced in 1.21
} else if (defaults.bool(forKey: "First Launch") == true && isKeyPresentInUserDefaults(key: "RefreshIntervalSeconds") == false ) {

defaults.set("🟢", forKey: "PreviousStateForNotification")
defaults.set(1200.0, forKey: "RefreshIntervalSeconds")


// this is where most returning users should end up and they need an initial state for the notifications
} else if defaults.bool(forKey: "First Launch") == true {

defaults.set("🟢", forKey: "PreviousStateForNotification")

// default config for new users
} else {

Expand All @@ -91,6 +99,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele
defaults.set(1, forKey:"FallingAQINotificationsWanted")
defaults.set(50, forKey:"FallingAQINotificationsTrigger")
defaults.set("🟢", forKey: "PreviousStateForNotification")
defaults.set(1200.0, forKey: "RefreshIntervalSeconds")
}

// Launching automatically at startup from tutorial: https://theswiftdev.com/how-to-launch-a-macos-app-at-login/
Expand All @@ -100,7 +109,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele
let isRunning = !runningApps.filter { $0.bundleIdentifier == launcherAppId }.isEmpty

SMLoginItemSetEnabled(launcherAppId as CFString, self.defaults.bool(forKey: "AutorunAtStartup"))

if isRunning {
DistributedNotificationCenter.default().post(name: .killLauncher, object: Bundle.main.bundleIdentifier!)
}
Expand All @@ -113,7 +122,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele
// menuFunctions().menuRefresh(NSMenuItem)

// periodically update the menu
_ = Timer.scheduledTimer(withTimeInterval: 1200.0, repeats: true) { timer in
_ = Timer.scheduledTimer(withTimeInterval: (AppDelegate().defaults.object(forKey:"RefreshIntervalSeconds") as? Double ?? Double()), repeats: true) { timer in
self.statusBarItemController = menuFunctions() }

}
Expand Down
Loading

0 comments on commit fbdd498

Please sign in to comment.