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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// Software Name: its-client
// SPDX-FileCopyrightText: Copyright (c) 2016-2022 Orange
// SPDX-License-Identifier: MIT License
//
// This software is distributed under the MIT license, see LICENSE.txt file for more details.
//
// Author: Frédéric GARDES <frederic.gardes@orange.com> et al.
// Software description: This Intelligent Transportation Systems (ITS) [MQTT](https://mqtt.org/) client based on the [JSon](https://www.json.org) [ETSI](https://www.etsi.org/committee/its) specification transcription provides a ready to connect project for the mobility (connected and autonomous vehicles, road side units, vulnerable road users,...).
pub mod geo_extension;
mod message_type;
mod parse_error;
mod queue;

use std::{cmp, convert, fmt, hash, str, str::FromStr};

use log::error;

use crate::analyse::configuration::Configuration;
use crate::mqtt::topic::geo_extension::{GeoExtension, Tile};
use crate::mqtt::topic::message_type::MessageType;
use crate::mqtt::topic::parse_error::ParseError;
use crate::mqtt::topic::queue::Queue;

#[derive(Default, Debug, Clone)]
// TODO implement a generic to manage a subscription with wild cards differently of a publish
pub struct Topic {
    // Project name at the topic root
    project: String,

    // Base topic
    queue: Queue,
    server: String,
    message_type: MessageType,

    // Source / destination extension: userUUID, roadUUID, oemUUID, appUUID, or +
    uuid: String,

    // GeoExtension
    pub geo_extension: GeoExtension,
}

impl Topic {
    fn empty() -> Topic {
        Topic {
            ..Default::default()
        }
    }

    pub(crate) fn new<Q, T>(
        queue: Option<Q>,
        message_type: Option<T>,
        uuid: Option<String>,
        geo_extension: Option<GeoExtension>,
    ) -> Topic
    where
        Q: Into<Queue> + Default,
        T: Into<MessageType> + Default,
    {
        Topic {
            project: "5GCroCo".to_string(),
            queue: match queue {
                Some(into_queue) => into_queue.into(),
                None => Queue::default(),
            },
            server: "v2x".to_string(),
            message_type: match message_type {
                Some(into_queue) => into_queue.into(),
                None => MessageType::default(),
            },
            uuid: uuid.unwrap_or("+".to_string()),
            geo_extension: geo_extension.unwrap_or_default(),

            ..Default::default()
        }
    }

    pub fn new_denm(component_name: String, geo_extension: &GeoExtension) -> Topic {
        Topic::new(
            Some("inQueue".to_string()),
            Some("denm".to_string()),
            Some(component_name),
            // assumed clone, we build a new topic
            Some(geo_extension.clone()),
        )
    }

    pub fn project_base(&self) -> String {
        format!(
            "{}/{}/{}/{}",
            self.project, self.queue, self.server, self.message_type
        )
    }

    // TODO find a better way to appropriate
    pub fn appropriate(&mut self, configuration: &Configuration) {
        self.uuid = configuration.component_name(None);
        self.queue = Queue::In;
    }
}

impl hash::Hash for Topic {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.project.hash(state);
        self.queue.hash(state);
        self.server.hash(state);
        self.message_type.hash(state);
        self.uuid.hash(state);
        self.geo_extension.hash(state);
    }
}

impl cmp::PartialEq for Topic {
    fn eq(&self, other: &Self) -> bool {
        self.project == other.project
            && self.queue == other.queue
            && self.server == other.server
            && self.message_type == other.message_type
            && self.uuid == other.uuid
            && self.geo_extension == other.geo_extension
    }
}

impl cmp::Eq for Topic {}

impl cmp::PartialEq<String> for Topic {
    fn eq(&self, other: &String) -> bool {
        match Topic::from_str(other) {
            Ok(topic) => self == &topic,
            Err(error) => {
                error!("We can't compare the topic with a bad string: {}", error);
                false
            }
        }
    }
}

impl convert::From<String> for Topic {
    fn from(topic: String) -> Self {
        Topic::from(topic.as_str())
    }
}

impl convert::From<&str> for Topic {
    fn from(topic: &str) -> Self {
        match Topic::from_str(topic) {
            Ok(topic) => topic,
            Err(error) => panic!(
                "Unable to convert the String {} as a Topic: {}, use from_str instead",
                topic, error
            ),
        }
    }
}

impl str::FromStr for Topic {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.trim_matches('/').split('/').enumerate().try_fold(
            Topic::empty(),
            |mut topic_struct, (i, element)| {
                match i {
                    // project
                    0 => topic_struct.project = element.to_string(),
                    // queue
                    1 => topic_struct.queue = Queue::from_str(element)?,
                    // server
                    2 => topic_struct.server = element.to_string(),
                    // message type
                    3 => topic_struct.message_type = MessageType::from_str(element)?,
                    // uuid
                    4 => topic_struct.uuid = element.to_string(),
                    // TODO use geo_extension FromStr trait instead
                    // geo extension
                    _n => {
                        let result = Tile::from_str(element)?;
                        topic_struct.geo_extension.tiles.push(result)
                    }
                }
                Ok(topic_struct)
            },
        )
    }
}

impl fmt::Display for Topic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}/{}{}",
            self.project_base(),
            self.uuid,
            self.geo_extension
        )
    }
}

#[cfg(test)]
mod tests {
    use crate::mqtt::topic::geo_extension::Tile;
    use crate::mqtt::topic::message_type::MessageType;
    use crate::mqtt::topic::queue::Queue;
    use crate::mqtt::topic::Topic;
    use std::str::FromStr;

    #[test]
    fn test_cam_topic_from_str() {
        let topic_string = "5GCroCo/outQueue/v2x/cam/car_1/0/1/2/3";
        let topic_result = Topic::from_str(topic_string);
        assert!(topic_result.is_ok());
        let topic = topic_result.unwrap();
        assert_eq!(topic.project, "5GCroCo".to_string());
        assert_eq!(topic.queue, Queue::Out);
        assert_eq!(topic.server, "v2x".to_string());
        assert_eq!(topic.message_type, MessageType::CAM);
        assert_eq!(topic.uuid, "car_1".to_string());
        assert_eq!(topic.geo_extension.tiles.len(), 4);
        for i in 0..4 {
            assert_eq!(topic.geo_extension.tiles[i], Tile::from(i as u8));
        }
    }

    #[test]
    fn test_denm_topic_from_str() {
        let topic_string =
            "5GCroCo/outQueue/v2x/denm/wse_app_bcn1/1/2/0/2/2/2/2/3/3/0/0/3/2/0/2/0/1/0/1/0/3/1/";
        let topic_result = Topic::from_str(topic_string);
        assert!(topic_result.is_ok());
        let topic = topic_result.unwrap();
        assert_eq!(topic.project, "5GCroCo".to_string());
        assert_eq!(topic.queue, Queue::Out);
        assert_eq!(topic.server, "v2x".to_string());
        assert_eq!(topic.message_type, MessageType::DENM);
        assert_eq!(topic.uuid, "wse_app_bcn1".to_string());
        assert_eq!(topic.geo_extension.tiles.len(), 22);
    }

    #[test]
    fn test_info_topic_from_str() {
        let topic_string = "5GCroCo/outQueue/v2x/info/broker";
        let topic_result = Topic::from_str(topic_string);
        assert!(topic_result.is_ok());
        let topic = topic_result.unwrap();
        assert_eq!(topic.project, "5GCroCo".to_string());
        assert_eq!(topic.queue, Queue::Out);
        assert_eq!(topic.server, "v2x".to_string());
        assert_eq!(topic.message_type, MessageType::INFO);
        assert_eq!(topic.uuid, "broker".to_string());
        assert_eq!(topic.geo_extension.tiles.len(), 0);
    }

    #[test]
    fn test_in_queue_cam_topic_from_str() {
        let topic_string = "5GCroCo/inQueue/v2x/cam/car_1/0/1/2/3";
        let topic_result = Topic::from_str(topic_string);
        assert!(topic_result.is_ok());
        let topic = topic_result.unwrap();
        assert_eq!(topic.project, "5GCroCo".to_string());
        assert_eq!(topic.queue, Queue::In);
        assert_eq!(topic.server, "v2x".to_string());
        assert_eq!(topic.message_type, MessageType::CAM);
        assert_eq!(topic.uuid, "car_1".to_string());
        assert_eq!(topic.geo_extension.tiles.len(), 4);
        for i in 0..4 {
            assert_eq!(topic.geo_extension.tiles[i], Tile::from(i as u8));
        }
    }
}