kdeconnect-proto 0.1.1

A pure Rust modular implementation of the KDE Connect protocol
Documentation
//! Define the [`PairPacket`] which is used during pairing of two devices.
use serde::{Deserialize, Serialize};

use crate::packet::{NetworkPacket, NetworkPacketBody};

/// The KDE Connect pair packet is used to negotiate pairing between devices.
///
/// <https://invent.kde.org/network/kdeconnect-meta/blob/master/protocol.md#kdeconnectpair>
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PairPacket {
    /// If true a pairing request is being accepted or a new one started. If false a pairing request
    /// is being rejected or a paired device is unpairing.
    pub pair: bool,

    /// Required if this is a pairing request. The current time in seconds since epoch. Used in the
    /// calculation of the pair verification code since protocol version 8.
    #[serde(deserialize_with = "super::deserialize_number_or_string_in_option")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub timestamp: Option<u64>,
}

impl NetworkPacket {
    /// Make a [`NetworkPacket`] with a [`PairPacket`] payload ready to make a pair request.
    pub fn pair_request(timestamp: u64) -> Self {
        NetworkPacket::new(NetworkPacketBody::Pair(PairPacket {
            pair: true,
            timestamp: Some(timestamp),
        }))
    }

    /// Make a [`NetworkPacket`] with a [`PairPacket`] payload ready to make a pair response.
    pub fn pair_response() -> Self {
        NetworkPacket::new(NetworkPacketBody::Pair(PairPacket {
            pair: true,
            timestamp: None,
        }))
    }

    /// Make a [`NetworkPacket`] with a [`PairPacket`] payload ready to make an unpair request.
    pub fn unpair_request() -> Self {
        NetworkPacket::new(NetworkPacketBody::Pair(PairPacket {
            pair: false,
            timestamp: None,
        }))
    }

    /// Make a [`NetworkPacket`] with a [`PairPacket`] payload ready to make an unpair responsee.
    pub fn unpair_response() -> Self {
        NetworkPacket::new(NetworkPacketBody::Pair(PairPacket {
            pair: false,
            timestamp: None,
        }))
    }
}