C8yMutableDevice

public class C8yMutableDevice : ObservableObject

Presents a C8Device device that can be observed for changed within in a SwiftUI View directly. Static device data is still available via the wrapped device attribute. In addition it provides dynamic data such as gps position, battery level, measurements etc that can be observed for changes

Use the EditableDevice class if you want to provide a view to allow a user to edit a device.

  • Wrapped device to which we want to add dynamic data

    Declaration

    Swift

    @Published
    public var device: C8yDevice { get set }
  • Current GPS location of device

    Declaration

    Swift

    @Published
    public var position: CLLocationCoordinate2D? { get set }
  • Returns a list of the move recent movement for this device based on emitted events for C8yLocationUpdate_EVENT This will return an empty set if no recent movement has been detected i.e. no recent events have been sent.

    Declaration

    Swift

    public var positionHistory: [CLLocationCoordinate2D] { get }

    Return Value

    List of CLLocationCoordinate2D with most recent being at the end of the array

  • Set to true if you want to load latest metrics for the device, value will reset back to false once reload has completed

    Declaration

    Swift

    @Published
    public var reloadMetrics: Bool { get set }
  • Set to true if you want to load latest logs for the device, value will reset back to false once reload has completed

    Declaration

    Swift

    @Published
    public var reloadLogs: Bool { get set }
  • Set to true if you want to load latest alarms for the device, value will reset back to false once reload has completed

    Declaration

    Swift

    @Published
    public var reloadAlarms: Bool { get set }
  • Set to true if you want to load latest operations history for the device, value will reset back to false once reload has completed

    Declaration

    Swift

    @Published
    public var reloadOperations: Bool { get set }
  • Set to true to activate maintenance mode for device in Cumulocity. @see toggleMaintenanceMode()

    Declaration

    Swift

    @Published
    public var maintenanceMode: Bool { get set }
  • Returns true if the device has been provisioned with its network.

    Declaration

    Swift

    @Published
    public private(set) var isDeployed: Bool { get set }
  • Returns the current battery level if available (returns -2 if not applicable)

    Declaration

    Swift

    @Published
    public private(set) var batteryLevel: Double { get set }
  • Returns the primary metric for this device e.g. Temperature, ambiance etc. This attribute is not observable as it can change too frequently, instead use the method primaryMetricPublisher(preferredMetric:refreshInterval:) along with the ‘onReceive’ SwiftUI event to ensure you can update your view fragment efficiently e.g.

    VStack(alignment: .leading) {
        Text("termperature is \(self.$primaryMeasurement.min)")
    }.onReceive(self.deviceWrapper.primaryMetricPublisher(preferredMetric: self.preferredMetric, refreshInterval: self.deviceRefreshInterval)) { v in
    
        print("received measurement: \(v) for \(self.deviceWrapper.device.name)")
        self.primaryMeasurement = v
    }
    

    Declaration

    Swift

    public private(set) var primaryMetric: Measurement { get }
  • Returns the primary metric history

    Declaration

    Swift

    @Published
    public private(set) var primaryMetricHistory: MeasurementSeries { get set }
  • Returns all available measurements captured by Cumulocity for this device

    Declaration

    Swift

    @Published
    public var measurements: [String : [C8yMeasurement]] { get set }
  • Returns all the latest events received by Cumulocity for the device

    Declaration

    Swift

    @Published
    public var events: [C8yEvent] { get set }
  • Returns all the latest alarms received by Cumulocity for the device

    Declaration

    Swift

    @Published
    public var alarms: [C8yAlarm] { get set }
  • Returns a list of all operations that are pending or completed that have been submitted to Cumulocity for this device

    Declaration

    Swift

    @Published
    public var operationHistory: [C8yOperation] { get set }
  • Indicates whether there is currently a background thread in place to periodically fetch the latest preferred metric and battery level Use the method startMonitorForPrimaryMetric(_:refreshInterval:)

    Declaration

    Swift

    public private(set) var isMonitoring: Bool { get }
  • Convenience attribute to try and detect if a device is currently being restarted, i.e. someone submitted a ‘c8y_Restart’ operation that is now flagged in Cumulocity as in the state ‘PENDING’ or ‘EXECUTING’, in which case this attribute returns true. Will be false once we receive an operation update for ‘c8y_Restart’ in operationHistory with an ulterior date and the state of either ‘COMPLETED’ or ‘FAILED’

    Declaration

    Swift

    @Published
    public var isRestarting: Bool { get set }
  • Convenience attribute that caches the last binary file associated with the device that was fetched from Cumulocity via the method attachmentForId(id) or posted via the method addAttachment(filename:fileType:content:)

    Declaration

    Swift

    public internal(set) var lastAttachment: JcMultiPartContent.ContentPart? { get }
  • Associated Cumulocity connection info that allows this object to fetch/post data

    Declaration

    Swift

    public var conn: C8yCumulocityConnection?
  • Default constructor representing a new C8yDevice

    Declaration

    Swift

    public init()
  • Constructor to create a mutable device for the give device

    Declaration

    Swift

    public init(_ device: C8yDevice, connection: C8yCumulocityConnection)

    Parameters

    device

    Device to which we want to fetch mutable data

    connection

    Connection details in order to connect to Cumulocity

  • Provides a publisher that can be used to listen for periodic updates to primary metric The refresh is based on the devices C8yDevice.requiredResponseInterval property

    Declaration

    Swift

    public func primaryMetricPublisher(preferredMetric: String?, autoRefresh: Bool = false) -> AnyPublisher<Measurement, Never>

    Parameters

    preferredMetric

    label of the measurement to periodically fetched requires both name and series separated by a dot ‘.’ e.g. ‘Temperature.T’

    autoRefresh

    set to true if you want the value to be refreshed automatically, false to only update once

    Return Value

    Publisher that will issue updated metrics periodically

  • Submits an operation to Cumulocity to ask the device to restart NOTE This will only work if supported by the device and its agent and might take several minutes or even hours before it is enacted

    Declaration

    Swift

    public func restart()
  • Sets the device’s requiredResponseInterval to -1 to trigger Cumulocity’s maintenance mode. Maintenance mode deactivates all of the devices alarms to avoid false flags. Calling this method if already in maintenance mode sets the requiredResponseInterval back to the last know value or 30 minutes if not known.

    Declaration

    Swift

    public func toggleMaintainanceMode() throws
  • Submits an operation to switch the relay and also synchronises the device relay attribute C8yDevice.relayState. NOTE - Only applicable if the device or agent supports it.

    Declaration

    Swift

    public func toggleRelay() throws
  • Updates the server side Cumulocity Managed Object based on the properties provided here.

    Throws

    Invalid key/value pair

    Declaration

    Swift

    public func updateDeviceProperty(withKey key: String, value: String) throws

    Parameters

    withKey

    name of the managed object attribute to updated/added

    value

    The value to be assigned

  • Provisions the netwok connection for the device. The implementation is provided via the appropriate network type C8yNetworks.provision(_:conn)

    This method does nothing If no specific network type is specified i.e. the device connects over standard ip public network

    Throws

    If network is invalid or not recognised

    Declaration

    Swift

    public func provision() throws -> AnyPublisher<C8yDevice, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Return Value

    Publisher with updated device

  • Deprovisions the netwok connection from the device. The implementation is provided via the appropriate network type C8yNetworks.deprovision(_:conn)

    This method does nothing If no specific network type is specified i.e. the device connects over standard ip public network

    Throws

    If network is invalid or not recognised

    Declaration

    Swift

    public func deprovision() throws -> AnyPublisher<C8yDevice, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Return Value

    Publisher with updated device

  • Deletes the device from Cumulocity, will first deprovision the device from it’s related network if it flagged as still being deployed isDeployed

    NOTE: If you are the using the C8yAssetCollection class to present your assets then you will need to also call the AssetCollection remove() method to remove the device locally.

    Throws

    if provisioned and network deprobvisioning failed.

    Declaration

    Swift

    public func delete() throws -> AnyPublisher<Bool, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Return Value

    Publisher with success/failure of operation

  • Submits the given operation to Cumulocity and records it in operationHistory The operation will have an initial status of PENDING

    Throws

    Invalid operation

    Declaration

    Swift

    public func sendOperation(_ op: C8yOperation) throws -> AnyPublisher<String, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Parameters

    operation

    The C8yOperation to be posted to Cumulocity for eventual execution by the device.

    Return Value

    Publisher with cumulocity internal id of new operation.

  • Submits the given event to Cumulocity and records it in events

    NOTE - C8yLocationUpdate_EVENT type events will also update the devices C8yMutableDevice.postion attribute as a side effect

    Throws

    Invalid event

    Declaration

    Swift

    public func sendEvent(_ event: C8yEvent) throws -> AnyPublisher<C8yEvent, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Parameters

    event

    The C8yEvent to be posted to Cumulocity for eventual execution by the device.

    Return Value

    Publisher with cumulocity internal id of new event.

  • Submits the new alarm to Cumulocity and records it in alarms The alarm will have an initial status of ACTIVE

    Throws

    Invalid alarm

    Declaration

    Swift

    public func postNewAlarm(type: String, severity: C8yAlarm.Severity, text: String) throws -> AnyPublisher<C8yAlarm, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Parameters

    type

    Describes the type of alarm being submitted.

    severity

    Either CRITICAL, MAJOR, MINOR or WARNING

    text

    Detailed description of alarm

    Return Value

    Publisher with new cumulocity alarm

  • Updates the existing alarm to Cumulocity and the copy in alarms

    Throws

    Invalid alarm

    Declaration

    Swift

    public func updateAlarm(_ alarm: C8yAlarm) throws -> AnyPublisher<C8yAlarm, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Parameters

    alarm

    Alarm to be updated in Cumulocity

    Return Value

    Publisher with updated cumulocity alarm

  • Convenience method to create a Managed Object containing only the device’s GPS position

    Declaration

    Swift

    public func toDevicePositionUpdate() -> C8yDevice

    Return Value

    Returns a C8yDevice instance referencing only the device internal id and it’s GPS position

  • Fetches latest device metrics, views will be updated automatically via published attribute measurements You must ensure that your SwiftUI View references this class object either as a @ObservedObject or @StateObject

    Declaration

    Swift

    public func updateMetricsForToday()
  • Fetches latest device metrics from Cumulocity

    Declaration

    Swift

    public func fetchAllMetricsForToday() -> AnyPublisher<[String : [C8yMeasurement]], JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Return Value

    Publisher containing latest device measurements

  • Fetches latest device event logs, views will be updated automatically via published attribute events You must ensure that your SwiftUI View references this class object either as a @ObservedObject or @StateObject

    Declaration

    Swift

    public func updateEventLogsForToday()
  • Fetches latest device events from Cumulocity

    Declaration

    Swift

    public func fetchEventLogsForToday() -> AnyPublisher<[C8yEvent], JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Return Value

    Publisher containing latest device events

  • Fetches latest device operation history, views will be updated automatically via published attribute operationHistory You must ensure that your SwiftUI View references this class object either as a @ObservedObject or @StateObject

    Declaration

    Swift

    public func updateOperationHistory()
  • Fetches latest device operation history from Cumulocity

    Declaration

    Swift

    public func fetchOperationHistory() -> AnyPublisher<[C8yOperation], JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Return Value

    Publisher containing latest operation history

  • Fetches latest device alarms, views will be updated automatically via published attribute alarms You must ensure that your SwiftUI View references this class object either as a @ObservedObject or @StateObject

    Declaration

    Swift

    public func updateAlarmsForToday()
  • Fetches latest device alarms from Cumulocity

    Declaration

    Swift

    public func fetchActiveAlarmsForToday() -> AnyPublisher<[C8yAlarm], JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Return Value

    Publisher containing latest alarms

  • Fetches latest device prefered metric from Cumulocity

    Declaration

    Swift

    public func fetchMostRecentPrimaryMetric(_ preferredMetric: String?) -> AnyPublisher<C8yMutableDevice.Measurement, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Return Value

    Publisher containing latest preferred metric

  • Initiates a background thread to periodically refetch the preferred metric from Cumulocity. Changes will be issued via the publisher returned from the method primaryMetricPublisher(preferredMetric:refreshInterval:)

    Declaration

    Swift

    public func startMonitorForPrimaryMetric(_ preferredMetric: String?, refreshInterval: Double, onFirstLoad: ((Double) -> Void)? = nil)

    Parameters

    preferredMetric

    label of the measurement to periodically fetched requires both name and series separated by a dot ‘.’ e.g. ‘Temperature.T’, if not provided will attempt to use first data point in dataPoints

    refreshInterval

    period in seconds in which to refresh values

    onFirstLoad

    callback, executed once first metrics have been successfully fetched, successful interval value is given

  • Stops the background thread for the preferred metric refresh and operation history. The thread must have been started by either startMonitorForPrimaryMetric(_:refreshInterval) or primaryMetricPublisher(preferredMetric:refreshInterval:)

    Declaration

    Swift

    public func stopMonitoring()
  • Starts a background thread to refresh operation history periodically

    Declaration

    Swift

    public func startMonitoringForOperationHistory(_ interval: TimeInterval = -1)

    Parameters

    refreshInterval

    period in seconds in which to refresh values

  • Returns the current status for given operation type, Will return only latest valeu if multiple operations exist for the same type

    Declaration

    Swift

    public func statusForOperation(_ type: String) -> C8yOperation?

    Parameters

    type

    The type of operation to be queried

    Return Value

    The latest operation for the given type or nil if none found

  • Downloads a binary attachment with the given id from Cumolocity and also caches the result in lastAttachment

    You can obtain a list of attachments related to this device via the attributeC8yDevice.attachments, If the attachment was uploaded via addAttachment(filename:fileType:content)

    Declaration

    Swift

    public func attachmentForId(id: String) -> AnyPublisher<JcMultiPartContent.ContentPart, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Parameters

    id

    c8y Internal id of binary attachment to be downloaded

    Return Value

    Publisher containing binary data

  • Uploads the given binary content to Cumulocity and updates the managed object associated with this device to record the resulting binary attachment id. The resulting id can be referenced via the string list attribute C8yDevice.attachments, which in turn is stored in Cumulocity via the attribute C8Y_MANAGED_OBJECTS_ATTACHMENTS

    Declaration

    Swift

    public func addAttachment(filename: String, fileType: String, content: Data) -> AnyPublisher<String, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Parameters

    filename

    name of file from which data originated

    fileType

    content type e.g. application/json or application/png

    content

    Binary data encoded in a Data object

    Return Value

    Publisher with cumulocity internal id associated with uploaded binary data

  • Replaces the existing attachment reference and uploades the content to Cumulocity. The existing attachment reference is replaced with the new one. It does delete the existing binary attachment from Cumulocity only the reference to existing attachment contained in the managed object attrbiute C8Y_MANAGED_OBJECTS_ATTACHMENTS and the device’s C8ytDevice.attachments attribute

    Declaration

    Swift

    public func replaceAttachment(index: Int, filename: String, fileType: String, content: Data) -> AnyPublisher<JcMultiPartContent.ContentPart?, JcConnectionRequest<C8yCumulocityConnection>.APIError>

    Parameters

    index

    Index into array C8yDevice.attachments to indicate which attachment should be replaced.

    filename

    name of file from which data originated

    fileType

    content type e.g. application/json or application/png

    content

    Binary data encoded in a Data object

    Return Value

    Publisher with cumulocity internal id associated with uploaded binary data

  • Undocumented

    See more

    Declaration

    Swift

    public struct MeasurementSeries
  • Undocumented

    See more

    Declaration

    Swift

    public struct Measurement