1pub mod abi;
33pub mod correlation;
34pub mod host;
35pub mod ids;
36pub mod settings;
37pub mod v1;
38
39pub use serde_json;
41pub use serde_json::{json, Map, Value};
42
43use base64::Engine as _;
44use serde::Serialize;
45
46pub const ABI_VERSION: i32 = 2;
48
49#[derive(Debug, Clone, PartialEq)]
52pub enum Event {
53 Message {
55 topic: String,
56 payload: Vec<u8>,
57 received: f64,
58 },
59 Intent {
62 adapter: String,
63 key: String,
64 id: String,
65 name: String,
66 params: Value,
67 expires: Option<f64>,
68 now: f64,
69 },
70 Tick { now: f64 },
72 Other(Value),
74}
75
76impl Event {
77 pub fn from_value(v: Value) -> Event {
80 let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned);
81 let f = |k: &str| v.get(k).and_then(Value::as_f64);
82 match v.get("event").and_then(Value::as_str) {
83 Some("message") => match (s("topic"), s("payload"), f("received")) {
84 (Some(topic), Some(p), Some(received)) => match hexs::b64_decode(&p) {
85 Some(payload) => Event::Message {
86 topic,
87 payload,
88 received,
89 },
90 None => Event::Other(v),
91 },
92 _ => Event::Other(v),
93 },
94 Some("intent") => match (s("adapter"), s("key"), s("id"), s("name"), f("now")) {
95 (Some(adapter), Some(key), Some(id), Some(name), Some(now)) => Event::Intent {
96 adapter,
97 key,
98 id,
99 name,
100 now,
101 params: v
102 .get("params")
103 .cloned()
104 .unwrap_or_else(|| Value::Object(Map::new())),
105 expires: f("expires"),
106 },
107 _ => Event::Other(v),
108 },
109 Some("tick") => match f("now") {
110 Some(now) => Event::Tick { now },
111 None => Event::Other(v),
112 },
113 _ => Event::Other(v),
114 }
115 }
116}
117
118#[derive(Debug, Clone, PartialEq, Serialize)]
120pub struct Publish {
121 pub topic: String,
122 pub payload: String,
124}
125
126#[derive(Debug, Clone, PartialEq, Serialize)]
129pub struct Protocol {
130 pub adapter: String,
131 pub key: String,
132 pub kind: String,
134 pub body: Value,
135}
136
137#[derive(Debug, Clone, PartialEq, Serialize)]
139pub struct LogLine {
140 pub level: &'static str,
141 pub message: String,
142}
143
144#[derive(Debug, Clone, Default, PartialEq, Serialize)]
147pub struct Answer {
148 #[serde(skip_serializing_if = "Vec::is_empty")]
149 pub publish: Vec<Publish>,
150 #[serde(skip_serializing_if = "Vec::is_empty")]
151 pub protocol: Vec<Protocol>,
152 #[serde(skip_serializing_if = "Vec::is_empty")]
153 pub log: Vec<LogLine>,
154 #[serde(flatten)]
155 pub extra: Map<String, Value>,
156}
157
158impl Answer {
159 pub fn publish(&mut self, topic: impl Into<String>, payload: impl AsRef<[u8]>) -> &mut Self {
161 self.publish.push(Publish {
162 topic: topic.into(),
163 payload: hexs::b64_encode(payload.as_ref()),
164 });
165 self
166 }
167
168 pub fn publish_json(&mut self, topic: impl Into<String>, value: &Value) -> &mut Self {
170 self.publish(topic, value.to_string())
171 }
172
173 pub fn protocol(
175 &mut self,
176 adapter: impl Into<String>,
177 key: impl Into<String>,
178 kind: &str,
179 body: Value,
180 ) -> &mut Self {
181 self.protocol.push(Protocol {
182 adapter: adapter.into(),
183 key: key.into(),
184 kind: kind.into(),
185 body,
186 });
187 self
188 }
189
190 pub fn result(&mut self, adapter: &str, key: &str, result: v1::CmdResult) -> &mut Self {
192 self.protocol(
193 adapter,
194 key,
195 "cmd/res",
196 serde_json::to_value(result).unwrap_or(Value::Null),
197 )
198 }
199
200 fn line(&mut self, level: &'static str, message: impl Into<String>) -> &mut Self {
201 self.log.push(LogLine {
202 level,
203 message: message.into(),
204 });
205 self
206 }
207
208 pub fn log_debug(&mut self, m: impl Into<String>) -> &mut Self {
209 self.line("debug", m)
210 }
211 pub fn log_info(&mut self, m: impl Into<String>) -> &mut Self {
212 self.line("info", m)
213 }
214 pub fn log_warning(&mut self, m: impl Into<String>) -> &mut Self {
215 self.line("warning", m)
216 }
217 pub fn log_error(&mut self, m: impl Into<String>) -> &mut Self {
218 self.line("error", m)
219 }
220}
221
222pub trait Package: Default {
227 fn handle(&mut self, event: Event) -> Answer;
228}
229
230pub mod hexs {
232 use super::*;
233
234 pub fn b64_encode(b: &[u8]) -> String {
235 base64::engine::general_purpose::STANDARD.encode(b)
236 }
237
238 pub fn b64_decode(s: &str) -> Option<Vec<u8>> {
239 base64::engine::general_purpose::STANDARD.decode(s).ok()
240 }
241
242 pub fn encode(b: &[u8]) -> String {
244 b.iter().map(|x| format!("{x:02x}")).collect()
245 }
246
247 pub fn decode(s: &str) -> Option<Vec<u8>> {
249 if s.len() % 2 != 0 || !s.is_ascii() {
250 return None;
251 }
252 (0..s.len())
253 .step_by(2)
254 .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
255 .collect()
256 }
257}
258
259#[macro_export]
261macro_rules! export {
262 ($t:ty) => {
263 ::std::thread_local! {
264 static PZ_PACKAGE: ::std::cell::RefCell<$t> = ::std::cell::RefCell::new(<$t>::default());
265 }
266
267 #[no_mangle]
268 pub extern "C" fn pz_abi() -> i32 {
269 $crate::ABI_VERSION
270 }
271
272 #[no_mangle]
273 pub extern "C" fn pz_alloc(len: i32) -> i32 {
274 $crate::abi::alloc(len)
275 }
276
277 #[no_mangle]
278 pub extern "C" fn pz_handle(ptr: i32, len: i32) -> i64 {
279 $crate::abi::handle(ptr, len, |event| PZ_PACKAGE.with(|p| p.borrow_mut().handle(event)))
280 }
281 };
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 #[test]
289 fn events_are_read_and_answers_written() {
290 let e = Event::from_value(
291 json!({"event": "message", "topic": "t/1", "payload": "aGk=", "received": 5.0}),
292 );
293 assert_eq!(
294 e,
295 Event::Message {
296 topic: "t/1".into(),
297 payload: b"hi".to_vec(),
298 received: 5.0
299 }
300 );
301 let i = Event::from_value(
302 json!({"event": "intent", "adapter": "x-1", "key": "gw:1", "id": "7",
303 "name": "reboot", "now": 1.0, "expires": null}),
304 );
305 assert!(matches!(i, Event::Intent { ref name, expires: None, .. } if name == "reboot"));
306 assert!(matches!(
307 Event::from_value(json!({"event": "call", "x": 1})),
308 Event::Other(_)
309 ));
310 assert!(matches!(
311 Event::from_value(json!({"event": "message", "topic": "t"})),
312 Event::Other(_)
313 ));
314
315 let mut a = Answer::default();
316 a.publish("t/down", b"hi")
317 .protocol("x-1", "gw:1", "state", json!({"v": 1}))
318 .log_info("ok");
319 a.result("x-1", "gw:1", v1::CmdResult::ok("7"));
320 assert_eq!(
321 serde_json::to_value(&a).unwrap(),
322 json!({
323 "publish": [{"topic": "t/down", "payload": "aGk="}],
324 "protocol": [{"adapter": "x-1", "key": "gw:1", "kind": "state", "body": {"v": 1}},
325 {"adapter": "x-1", "key": "gw:1", "kind": "cmd/res", "body": {"v": 1, "id": "7", "status": "ok"}}],
326 "log": [{"level": "info", "message": "ok"}]})
327 );
328 assert_eq!(serde_json::to_value(Answer::default()).unwrap(), json!({}));
329 assert_eq!(hexs::decode("0aFF"), Some(vec![10, 255]));
330 assert_eq!(hexs::encode(&[10, 255]), "0aff");
331 assert_eq!(hexs::decode("abc"), None);
332 }
333}