i2cbus_api/server/
mod.rs

1use std::marker::PhantomData;
2use futures::{Future, future, Stream, stream};
3use hyper;
4use hyper::{Request, Response, Error, StatusCode, Body, HeaderMap};
5use hyper::header::{HeaderName, HeaderValue, CONTENT_TYPE};
6use log::warn;
7use serde_json;
8#[allow(unused_imports)]
9use std::convert::{TryFrom, TryInto};
10use std::io;
11use url::form_urlencoded;
12#[allow(unused_imports)]
13use swagger;
14use swagger::{ApiError, XSpanIdString, Has, RequestParser};
15pub use swagger::auth::Authorization;
16use swagger::auth::Scopes;
17use swagger::context::ContextualPayload;
18
19#[allow(unused_imports)]
20use crate::models;
21use crate::header;
22
23pub use crate::context;
24
25use crate::{Api,
26     I2cBusApiResponse,
27     I2cBusListResponse,
28     I2cBusReadByteResponse,
29     I2cBusReadBytesResponse,
30     I2cBusReadRegResponse,
31     I2cBusWriteByteResponse,
32     I2cBusWriteByteRegResponse,
33     I2cBusWriteBytesResponse,
34     I2cBusWriteBytesRegResponse
35};
36
37mod paths {
38    use lazy_static::lazy_static;
39
40    lazy_static! {
41        pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(vec![
42            r"^/i2c/api$",
43            r"^/i2c/buslist$",
44            r"^/i2c/(?P<busId>[^/?#]*)/read/byte/(?P<addr>[^/?#]*)$",
45            r"^/i2c/(?P<busId>[^/?#]*)/read/bytes/(?P<addr>[^/?#]*)/(?P<numBytes>[^/?#]*)$",
46            r"^/i2c/(?P<busId>[^/?#]*)/read/reg/(?P<addr>[^/?#]*)/(?P<reg>[^/?#]*)/(?P<numBytes>[^/?#]*)$",
47            r"^/i2c/(?P<busId>[^/?#]*)/write/byte/reg/(?P<addr>[^/?#]*)/(?P<reg>[^/?#]*)/(?P<value>[^/?#]*)$",
48            r"^/i2c/(?P<busId>[^/?#]*)/write/byte/(?P<addr>[^/?#]*)/(?P<value>[^/?#]*)$",
49            r"^/i2c/(?P<busId>[^/?#]*)/write/bytes/reg/(?P<addr>[^/?#]*)/(?P<reg>[^/?#]*)$",
50            r"^/i2c/(?P<busId>[^/?#]*)/write/bytes/(?P<addr>[^/?#]*)$"
51        ])
52        .expect("Unable to create global regex set");
53    }
54    pub(crate) static ID_I2C_API: usize = 0;
55    pub(crate) static ID_I2C_BUSLIST: usize = 1;
56    pub(crate) static ID_I2C_BUSID_READ_BYTE_ADDR: usize = 2;
57    lazy_static! {
58        pub static ref REGEX_I2C_BUSID_READ_BYTE_ADDR: regex::Regex =
59            regex::Regex::new(r"^/i2c/(?P<busId>[^/?#]*)/read/byte/(?P<addr>[^/?#]*)$")
60                .expect("Unable to create regex for I2C_BUSID_READ_BYTE_ADDR");
61    }
62    pub(crate) static ID_I2C_BUSID_READ_BYTES_ADDR_NUMBYTES: usize = 3;
63    lazy_static! {
64        pub static ref REGEX_I2C_BUSID_READ_BYTES_ADDR_NUMBYTES: regex::Regex =
65            regex::Regex::new(r"^/i2c/(?P<busId>[^/?#]*)/read/bytes/(?P<addr>[^/?#]*)/(?P<numBytes>[^/?#]*)$")
66                .expect("Unable to create regex for I2C_BUSID_READ_BYTES_ADDR_NUMBYTES");
67    }
68    pub(crate) static ID_I2C_BUSID_READ_REG_ADDR_REG_NUMBYTES: usize = 4;
69    lazy_static! {
70        pub static ref REGEX_I2C_BUSID_READ_REG_ADDR_REG_NUMBYTES: regex::Regex =
71            regex::Regex::new(r"^/i2c/(?P<busId>[^/?#]*)/read/reg/(?P<addr>[^/?#]*)/(?P<reg>[^/?#]*)/(?P<numBytes>[^/?#]*)$")
72                .expect("Unable to create regex for I2C_BUSID_READ_REG_ADDR_REG_NUMBYTES");
73    }
74    pub(crate) static ID_I2C_BUSID_WRITE_BYTE_REG_ADDR_REG_VALUE: usize = 5;
75    lazy_static! {
76        pub static ref REGEX_I2C_BUSID_WRITE_BYTE_REG_ADDR_REG_VALUE: regex::Regex =
77            regex::Regex::new(r"^/i2c/(?P<busId>[^/?#]*)/write/byte/reg/(?P<addr>[^/?#]*)/(?P<reg>[^/?#]*)/(?P<value>[^/?#]*)$")
78                .expect("Unable to create regex for I2C_BUSID_WRITE_BYTE_REG_ADDR_REG_VALUE");
79    }
80    pub(crate) static ID_I2C_BUSID_WRITE_BYTE_ADDR_VALUE: usize = 6;
81    lazy_static! {
82        pub static ref REGEX_I2C_BUSID_WRITE_BYTE_ADDR_VALUE: regex::Regex =
83            regex::Regex::new(r"^/i2c/(?P<busId>[^/?#]*)/write/byte/(?P<addr>[^/?#]*)/(?P<value>[^/?#]*)$")
84                .expect("Unable to create regex for I2C_BUSID_WRITE_BYTE_ADDR_VALUE");
85    }
86    pub(crate) static ID_I2C_BUSID_WRITE_BYTES_REG_ADDR_REG: usize = 7;
87    lazy_static! {
88        pub static ref REGEX_I2C_BUSID_WRITE_BYTES_REG_ADDR_REG: regex::Regex =
89            regex::Regex::new(r"^/i2c/(?P<busId>[^/?#]*)/write/bytes/reg/(?P<addr>[^/?#]*)/(?P<reg>[^/?#]*)$")
90                .expect("Unable to create regex for I2C_BUSID_WRITE_BYTES_REG_ADDR_REG");
91    }
92    pub(crate) static ID_I2C_BUSID_WRITE_BYTES_ADDR: usize = 8;
93    lazy_static! {
94        pub static ref REGEX_I2C_BUSID_WRITE_BYTES_ADDR: regex::Regex =
95            regex::Regex::new(r"^/i2c/(?P<busId>[^/?#]*)/write/bytes/(?P<addr>[^/?#]*)$")
96                .expect("Unable to create regex for I2C_BUSID_WRITE_BYTES_ADDR");
97    }
98}
99
100pub struct MakeService<T, RC> {
101    api_impl: T,
102    marker: PhantomData<RC>,
103}
104
105impl<T, RC> MakeService<T, RC>
106where
107    T: Api<RC> + Clone + Send + 'static,
108    RC: Has<XSpanIdString>  + 'static
109{
110    pub fn new(api_impl: T) -> Self {
111        MakeService {
112            api_impl,
113            marker: PhantomData
114        }
115    }
116}
117
118impl<'a, T, SC, RC> hyper::service::MakeService<&'a SC> for MakeService<T, RC>
119where
120    T: Api<RC> + Clone + Send + 'static,
121    RC: Has<XSpanIdString>  + 'static + Send
122{
123    type ReqBody = ContextualPayload<Body, RC>;
124    type ResBody = Body;
125    type Error = Error;
126    type Service = Service<T, RC>;
127    type Future = future::FutureResult<Self::Service, Self::MakeError>;
128    type MakeError = Error;
129
130    fn make_service(&mut self, _ctx: &'a SC) -> Self::Future {
131        future::FutureResult::from(Ok(Service::new(
132            self.api_impl.clone(),
133        )))
134    }
135}
136
137type ServiceFuture = Box<dyn Future<Item = Response<Body>, Error = Error> + Send>;
138
139fn method_not_allowed() -> ServiceFuture {
140    Box::new(future::ok(
141        Response::builder().status(StatusCode::METHOD_NOT_ALLOWED)
142            .body(Body::empty())
143            .expect("Unable to create Method Not Allowed response")
144    ))
145}
146
147pub struct Service<T, RC> {
148    api_impl: T,
149    marker: PhantomData<RC>,
150}
151
152impl<T, RC> Service<T, RC>
153where
154    T: Api<RC> + Clone + Send + 'static,
155    RC: Has<XSpanIdString>  + 'static {
156    pub fn new(api_impl: T) -> Self {
157        Service {
158            api_impl: api_impl,
159            marker: PhantomData
160        }
161    }
162}
163
164impl<T, C> hyper::service::Service for Service<T, C>
165where
166    T: Api<C> + Clone + Send + 'static,
167    C: Has<XSpanIdString>  + 'static + Send
168{
169    type ReqBody = ContextualPayload<Body, C>;
170    type ResBody = Body;
171    type Error = Error;
172    type Future = ServiceFuture;
173
174    fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future {
175        let api_impl = self.api_impl.clone();
176        let (parts, body) = req.into_parts();
177        let (method, uri, headers) = (parts.method, parts.uri, parts.headers);
178        let path = paths::GLOBAL_REGEX_SET.matches(uri.path());
179        let mut context = body.context;
180        let body = body.inner;
181
182        match &method {
183
184            // I2cBusApi - GET /i2c/api
185            &hyper::Method::GET if path.matched(paths::ID_I2C_API) => {
186                Box::new({
187                        {{
188                                Box::new(
189                                    api_impl.i2c_bus_api(
190                                        &context
191                                    ).then(move |result| {
192                                        let mut response = Response::new(Body::empty());
193                                        response.headers_mut().insert(
194                                            HeaderName::from_static("x-span-id"),
195                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
196                                                .expect("Unable to create X-Span-ID header value"));
197
198                                        match result {
199                                            Ok(rsp) => match rsp {
200                                                I2cBusApiResponse::OK
201                                                    (body)
202                                                => {
203                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
204                                                    response.headers_mut().insert(
205                                                        CONTENT_TYPE,
206                                                        HeaderValue::from_str("text/x-yaml")
207                                                            .expect("Unable to create Content-Type header for I2C_BUS_API_OK"));
208                                                    let body = body;
209                                                    *response.body_mut() = Body::from(body);
210                                                },
211                                                I2cBusApiResponse::FileNotFound
212                                                    (body)
213                                                => {
214                                                    *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode");
215                                                    response.headers_mut().insert(
216                                                        CONTENT_TYPE,
217                                                        HeaderValue::from_str("text/plain")
218                                                            .expect("Unable to create Content-Type header for I2C_BUS_API_FILE_NOT_FOUND"));
219                                                    let body = body;
220                                                    *response.body_mut() = Body::from(body);
221                                                },
222                                            },
223                                            Err(_) => {
224                                                // Application code returned an error. This should not happen, as the implementation should
225                                                // return a valid response.
226                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
227                                                *response.body_mut() = Body::from("An internal error occurred");
228                                            },
229                                        }
230
231                                        future::ok(response)
232                                    }
233                                ))
234                        }}
235                }) as Self::Future
236            },
237
238            // I2cBusList - GET /i2c/buslist
239            &hyper::Method::GET if path.matched(paths::ID_I2C_BUSLIST) => {
240                Box::new({
241                        {{
242                                Box::new(
243                                    api_impl.i2c_bus_list(
244                                        &context
245                                    ).then(move |result| {
246                                        let mut response = Response::new(Body::empty());
247                                        response.headers_mut().insert(
248                                            HeaderName::from_static("x-span-id"),
249                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
250                                                .expect("Unable to create X-Span-ID header value"));
251
252                                        match result {
253                                            Ok(rsp) => match rsp {
254                                                I2cBusListResponse::OK
255                                                    (body)
256                                                => {
257                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
258                                                    response.headers_mut().insert(
259                                                        CONTENT_TYPE,
260                                                        HeaderValue::from_str("application/json")
261                                                            .expect("Unable to create Content-Type header for I2C_BUS_LIST_OK"));
262                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
263                                                    *response.body_mut() = Body::from(body);
264                                                },
265                                            },
266                                            Err(_) => {
267                                                // Application code returned an error. This should not happen, as the implementation should
268                                                // return a valid response.
269                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
270                                                *response.body_mut() = Body::from("An internal error occurred");
271                                            },
272                                        }
273
274                                        future::ok(response)
275                                    }
276                                ))
277                        }}
278                }) as Self::Future
279            },
280
281            // I2cBusReadByte - GET /i2c/{busId}/read/byte/{addr}
282            &hyper::Method::GET if path.matched(paths::ID_I2C_BUSID_READ_BYTE_ADDR) => {
283                // Path parameters
284                let path: &str = &uri.path().to_string();
285                let path_params =
286                    paths::REGEX_I2C_BUSID_READ_BYTE_ADDR
287                    .captures(&path)
288                    .unwrap_or_else(||
289                        panic!("Path {} matched RE I2C_BUSID_READ_BYTE_ADDR in set but failed match against \"{}\"", path, paths::REGEX_I2C_BUSID_READ_BYTE_ADDR.as_str())
290                    );
291
292                let param_bus_id = match percent_encoding::percent_decode(path_params["busId"].as_bytes()).decode_utf8() {
293                    Ok(param_bus_id) => match param_bus_id.parse::<i32>() {
294                        Ok(param_bus_id) => param_bus_id,
295                        Err(e) => return Box::new(future::ok(Response::builder()
296                                        .status(StatusCode::BAD_REQUEST)
297                                        .body(Body::from(format!("Couldn't parse path parameter busId: {}", e)))
298                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
299                    },
300                    Err(_) => return Box::new(future::ok(Response::builder()
301                                        .status(StatusCode::BAD_REQUEST)
302                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["busId"])))
303                                        .expect("Unable to create Bad Request response for invalid percent decode")))
304                };
305
306                let param_addr = match percent_encoding::percent_decode(path_params["addr"].as_bytes()).decode_utf8() {
307                    Ok(param_addr) => match param_addr.parse::<i32>() {
308                        Ok(param_addr) => param_addr,
309                        Err(e) => return Box::new(future::ok(Response::builder()
310                                        .status(StatusCode::BAD_REQUEST)
311                                        .body(Body::from(format!("Couldn't parse path parameter addr: {}", e)))
312                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
313                    },
314                    Err(_) => return Box::new(future::ok(Response::builder()
315                                        .status(StatusCode::BAD_REQUEST)
316                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["addr"])))
317                                        .expect("Unable to create Bad Request response for invalid percent decode")))
318                };
319
320                Box::new({
321                        {{
322                                Box::new(
323                                    api_impl.i2c_bus_read_byte(
324                                            param_bus_id,
325                                            param_addr,
326                                        &context
327                                    ).then(move |result| {
328                                        let mut response = Response::new(Body::empty());
329                                        response.headers_mut().insert(
330                                            HeaderName::from_static("x-span-id"),
331                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
332                                                .expect("Unable to create X-Span-ID header value"));
333
334                                        match result {
335                                            Ok(rsp) => match rsp {
336                                                I2cBusReadByteResponse::OK
337                                                    (body)
338                                                => {
339                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
340                                                    response.headers_mut().insert(
341                                                        CONTENT_TYPE,
342                                                        HeaderValue::from_str("application/json")
343                                                            .expect("Unable to create Content-Type header for I2C_BUS_READ_BYTE_OK"));
344                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
345                                                    *response.body_mut() = Body::from(body);
346                                                },
347                                                I2cBusReadByteResponse::BadRequest
348                                                    (body)
349                                                => {
350                                                    *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode");
351                                                    response.headers_mut().insert(
352                                                        CONTENT_TYPE,
353                                                        HeaderValue::from_str("application/json")
354                                                            .expect("Unable to create Content-Type header for I2C_BUS_READ_BYTE_BAD_REQUEST"));
355                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
356                                                    *response.body_mut() = Body::from(body);
357                                                },
358                                                I2cBusReadByteResponse::TransactionFailed
359                                                    (body)
360                                                => {
361                                                    *response.status_mut() = StatusCode::from_u16(502).expect("Unable to turn 502 into a StatusCode");
362                                                    response.headers_mut().insert(
363                                                        CONTENT_TYPE,
364                                                        HeaderValue::from_str("application/json")
365                                                            .expect("Unable to create Content-Type header for I2C_BUS_READ_BYTE_TRANSACTION_FAILED"));
366                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
367                                                    *response.body_mut() = Body::from(body);
368                                                },
369                                            },
370                                            Err(_) => {
371                                                // Application code returned an error. This should not happen, as the implementation should
372                                                // return a valid response.
373                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
374                                                *response.body_mut() = Body::from("An internal error occurred");
375                                            },
376                                        }
377
378                                        future::ok(response)
379                                    }
380                                ))
381                        }}
382                }) as Self::Future
383            },
384
385            // I2cBusReadBytes - GET /i2c/{busId}/read/bytes/{addr}/{numBytes}
386            &hyper::Method::GET if path.matched(paths::ID_I2C_BUSID_READ_BYTES_ADDR_NUMBYTES) => {
387                // Path parameters
388                let path: &str = &uri.path().to_string();
389                let path_params =
390                    paths::REGEX_I2C_BUSID_READ_BYTES_ADDR_NUMBYTES
391                    .captures(&path)
392                    .unwrap_or_else(||
393                        panic!("Path {} matched RE I2C_BUSID_READ_BYTES_ADDR_NUMBYTES in set but failed match against \"{}\"", path, paths::REGEX_I2C_BUSID_READ_BYTES_ADDR_NUMBYTES.as_str())
394                    );
395
396                let param_bus_id = match percent_encoding::percent_decode(path_params["busId"].as_bytes()).decode_utf8() {
397                    Ok(param_bus_id) => match param_bus_id.parse::<i32>() {
398                        Ok(param_bus_id) => param_bus_id,
399                        Err(e) => return Box::new(future::ok(Response::builder()
400                                        .status(StatusCode::BAD_REQUEST)
401                                        .body(Body::from(format!("Couldn't parse path parameter busId: {}", e)))
402                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
403                    },
404                    Err(_) => return Box::new(future::ok(Response::builder()
405                                        .status(StatusCode::BAD_REQUEST)
406                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["busId"])))
407                                        .expect("Unable to create Bad Request response for invalid percent decode")))
408                };
409
410                let param_addr = match percent_encoding::percent_decode(path_params["addr"].as_bytes()).decode_utf8() {
411                    Ok(param_addr) => match param_addr.parse::<i32>() {
412                        Ok(param_addr) => param_addr,
413                        Err(e) => return Box::new(future::ok(Response::builder()
414                                        .status(StatusCode::BAD_REQUEST)
415                                        .body(Body::from(format!("Couldn't parse path parameter addr: {}", e)))
416                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
417                    },
418                    Err(_) => return Box::new(future::ok(Response::builder()
419                                        .status(StatusCode::BAD_REQUEST)
420                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["addr"])))
421                                        .expect("Unable to create Bad Request response for invalid percent decode")))
422                };
423
424                let param_num_bytes = match percent_encoding::percent_decode(path_params["numBytes"].as_bytes()).decode_utf8() {
425                    Ok(param_num_bytes) => match param_num_bytes.parse::<i32>() {
426                        Ok(param_num_bytes) => param_num_bytes,
427                        Err(e) => return Box::new(future::ok(Response::builder()
428                                        .status(StatusCode::BAD_REQUEST)
429                                        .body(Body::from(format!("Couldn't parse path parameter numBytes: {}", e)))
430                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
431                    },
432                    Err(_) => return Box::new(future::ok(Response::builder()
433                                        .status(StatusCode::BAD_REQUEST)
434                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["numBytes"])))
435                                        .expect("Unable to create Bad Request response for invalid percent decode")))
436                };
437
438                Box::new({
439                        {{
440                                Box::new(
441                                    api_impl.i2c_bus_read_bytes(
442                                            param_bus_id,
443                                            param_addr,
444                                            param_num_bytes,
445                                        &context
446                                    ).then(move |result| {
447                                        let mut response = Response::new(Body::empty());
448                                        response.headers_mut().insert(
449                                            HeaderName::from_static("x-span-id"),
450                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
451                                                .expect("Unable to create X-Span-ID header value"));
452
453                                        match result {
454                                            Ok(rsp) => match rsp {
455                                                I2cBusReadBytesResponse::OK
456                                                    (body)
457                                                => {
458                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
459                                                    response.headers_mut().insert(
460                                                        CONTENT_TYPE,
461                                                        HeaderValue::from_str("application/json")
462                                                            .expect("Unable to create Content-Type header for I2C_BUS_READ_BYTES_OK"));
463                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
464                                                    *response.body_mut() = Body::from(body);
465                                                },
466                                                I2cBusReadBytesResponse::BadRequest
467                                                    (body)
468                                                => {
469                                                    *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode");
470                                                    response.headers_mut().insert(
471                                                        CONTENT_TYPE,
472                                                        HeaderValue::from_str("application/json")
473                                                            .expect("Unable to create Content-Type header for I2C_BUS_READ_BYTES_BAD_REQUEST"));
474                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
475                                                    *response.body_mut() = Body::from(body);
476                                                },
477                                                I2cBusReadBytesResponse::TransactionFailed
478                                                    (body)
479                                                => {
480                                                    *response.status_mut() = StatusCode::from_u16(502).expect("Unable to turn 502 into a StatusCode");
481                                                    response.headers_mut().insert(
482                                                        CONTENT_TYPE,
483                                                        HeaderValue::from_str("application/json")
484                                                            .expect("Unable to create Content-Type header for I2C_BUS_READ_BYTES_TRANSACTION_FAILED"));
485                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
486                                                    *response.body_mut() = Body::from(body);
487                                                },
488                                            },
489                                            Err(_) => {
490                                                // Application code returned an error. This should not happen, as the implementation should
491                                                // return a valid response.
492                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
493                                                *response.body_mut() = Body::from("An internal error occurred");
494                                            },
495                                        }
496
497                                        future::ok(response)
498                                    }
499                                ))
500                        }}
501                }) as Self::Future
502            },
503
504            // I2cBusReadReg - GET /i2c/{busId}/read/reg/{addr}/{reg}/{numBytes}
505            &hyper::Method::GET if path.matched(paths::ID_I2C_BUSID_READ_REG_ADDR_REG_NUMBYTES) => {
506                // Path parameters
507                let path: &str = &uri.path().to_string();
508                let path_params =
509                    paths::REGEX_I2C_BUSID_READ_REG_ADDR_REG_NUMBYTES
510                    .captures(&path)
511                    .unwrap_or_else(||
512                        panic!("Path {} matched RE I2C_BUSID_READ_REG_ADDR_REG_NUMBYTES in set but failed match against \"{}\"", path, paths::REGEX_I2C_BUSID_READ_REG_ADDR_REG_NUMBYTES.as_str())
513                    );
514
515                let param_bus_id = match percent_encoding::percent_decode(path_params["busId"].as_bytes()).decode_utf8() {
516                    Ok(param_bus_id) => match param_bus_id.parse::<i32>() {
517                        Ok(param_bus_id) => param_bus_id,
518                        Err(e) => return Box::new(future::ok(Response::builder()
519                                        .status(StatusCode::BAD_REQUEST)
520                                        .body(Body::from(format!("Couldn't parse path parameter busId: {}", e)))
521                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
522                    },
523                    Err(_) => return Box::new(future::ok(Response::builder()
524                                        .status(StatusCode::BAD_REQUEST)
525                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["busId"])))
526                                        .expect("Unable to create Bad Request response for invalid percent decode")))
527                };
528
529                let param_addr = match percent_encoding::percent_decode(path_params["addr"].as_bytes()).decode_utf8() {
530                    Ok(param_addr) => match param_addr.parse::<i32>() {
531                        Ok(param_addr) => param_addr,
532                        Err(e) => return Box::new(future::ok(Response::builder()
533                                        .status(StatusCode::BAD_REQUEST)
534                                        .body(Body::from(format!("Couldn't parse path parameter addr: {}", e)))
535                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
536                    },
537                    Err(_) => return Box::new(future::ok(Response::builder()
538                                        .status(StatusCode::BAD_REQUEST)
539                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["addr"])))
540                                        .expect("Unable to create Bad Request response for invalid percent decode")))
541                };
542
543                let param_reg = match percent_encoding::percent_decode(path_params["reg"].as_bytes()).decode_utf8() {
544                    Ok(param_reg) => match param_reg.parse::<i32>() {
545                        Ok(param_reg) => param_reg,
546                        Err(e) => return Box::new(future::ok(Response::builder()
547                                        .status(StatusCode::BAD_REQUEST)
548                                        .body(Body::from(format!("Couldn't parse path parameter reg: {}", e)))
549                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
550                    },
551                    Err(_) => return Box::new(future::ok(Response::builder()
552                                        .status(StatusCode::BAD_REQUEST)
553                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["reg"])))
554                                        .expect("Unable to create Bad Request response for invalid percent decode")))
555                };
556
557                let param_num_bytes = match percent_encoding::percent_decode(path_params["numBytes"].as_bytes()).decode_utf8() {
558                    Ok(param_num_bytes) => match param_num_bytes.parse::<i32>() {
559                        Ok(param_num_bytes) => param_num_bytes,
560                        Err(e) => return Box::new(future::ok(Response::builder()
561                                        .status(StatusCode::BAD_REQUEST)
562                                        .body(Body::from(format!("Couldn't parse path parameter numBytes: {}", e)))
563                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
564                    },
565                    Err(_) => return Box::new(future::ok(Response::builder()
566                                        .status(StatusCode::BAD_REQUEST)
567                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["numBytes"])))
568                                        .expect("Unable to create Bad Request response for invalid percent decode")))
569                };
570
571                Box::new({
572                        {{
573                                Box::new(
574                                    api_impl.i2c_bus_read_reg(
575                                            param_bus_id,
576                                            param_addr,
577                                            param_reg,
578                                            param_num_bytes,
579                                        &context
580                                    ).then(move |result| {
581                                        let mut response = Response::new(Body::empty());
582                                        response.headers_mut().insert(
583                                            HeaderName::from_static("x-span-id"),
584                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
585                                                .expect("Unable to create X-Span-ID header value"));
586
587                                        match result {
588                                            Ok(rsp) => match rsp {
589                                                I2cBusReadRegResponse::OK
590                                                    (body)
591                                                => {
592                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
593                                                    response.headers_mut().insert(
594                                                        CONTENT_TYPE,
595                                                        HeaderValue::from_str("application/json")
596                                                            .expect("Unable to create Content-Type header for I2C_BUS_READ_REG_OK"));
597                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
598                                                    *response.body_mut() = Body::from(body);
599                                                },
600                                                I2cBusReadRegResponse::BadRequest
601                                                    (body)
602                                                => {
603                                                    *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode");
604                                                    response.headers_mut().insert(
605                                                        CONTENT_TYPE,
606                                                        HeaderValue::from_str("application/json")
607                                                            .expect("Unable to create Content-Type header for I2C_BUS_READ_REG_BAD_REQUEST"));
608                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
609                                                    *response.body_mut() = Body::from(body);
610                                                },
611                                                I2cBusReadRegResponse::TransactionFailed
612                                                    (body)
613                                                => {
614                                                    *response.status_mut() = StatusCode::from_u16(502).expect("Unable to turn 502 into a StatusCode");
615                                                    response.headers_mut().insert(
616                                                        CONTENT_TYPE,
617                                                        HeaderValue::from_str("application/json")
618                                                            .expect("Unable to create Content-Type header for I2C_BUS_READ_REG_TRANSACTION_FAILED"));
619                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
620                                                    *response.body_mut() = Body::from(body);
621                                                },
622                                            },
623                                            Err(_) => {
624                                                // Application code returned an error. This should not happen, as the implementation should
625                                                // return a valid response.
626                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
627                                                *response.body_mut() = Body::from("An internal error occurred");
628                                            },
629                                        }
630
631                                        future::ok(response)
632                                    }
633                                ))
634                        }}
635                }) as Self::Future
636            },
637
638            // I2cBusWriteByte - POST /i2c/{busId}/write/byte/{addr}/{value}
639            &hyper::Method::POST if path.matched(paths::ID_I2C_BUSID_WRITE_BYTE_ADDR_VALUE) => {
640                // Path parameters
641                let path: &str = &uri.path().to_string();
642                let path_params =
643                    paths::REGEX_I2C_BUSID_WRITE_BYTE_ADDR_VALUE
644                    .captures(&path)
645                    .unwrap_or_else(||
646                        panic!("Path {} matched RE I2C_BUSID_WRITE_BYTE_ADDR_VALUE in set but failed match against \"{}\"", path, paths::REGEX_I2C_BUSID_WRITE_BYTE_ADDR_VALUE.as_str())
647                    );
648
649                let param_bus_id = match percent_encoding::percent_decode(path_params["busId"].as_bytes()).decode_utf8() {
650                    Ok(param_bus_id) => match param_bus_id.parse::<i32>() {
651                        Ok(param_bus_id) => param_bus_id,
652                        Err(e) => return Box::new(future::ok(Response::builder()
653                                        .status(StatusCode::BAD_REQUEST)
654                                        .body(Body::from(format!("Couldn't parse path parameter busId: {}", e)))
655                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
656                    },
657                    Err(_) => return Box::new(future::ok(Response::builder()
658                                        .status(StatusCode::BAD_REQUEST)
659                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["busId"])))
660                                        .expect("Unable to create Bad Request response for invalid percent decode")))
661                };
662
663                let param_addr = match percent_encoding::percent_decode(path_params["addr"].as_bytes()).decode_utf8() {
664                    Ok(param_addr) => match param_addr.parse::<i32>() {
665                        Ok(param_addr) => param_addr,
666                        Err(e) => return Box::new(future::ok(Response::builder()
667                                        .status(StatusCode::BAD_REQUEST)
668                                        .body(Body::from(format!("Couldn't parse path parameter addr: {}", e)))
669                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
670                    },
671                    Err(_) => return Box::new(future::ok(Response::builder()
672                                        .status(StatusCode::BAD_REQUEST)
673                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["addr"])))
674                                        .expect("Unable to create Bad Request response for invalid percent decode")))
675                };
676
677                let param_value = match percent_encoding::percent_decode(path_params["value"].as_bytes()).decode_utf8() {
678                    Ok(param_value) => match param_value.parse::<i32>() {
679                        Ok(param_value) => param_value,
680                        Err(e) => return Box::new(future::ok(Response::builder()
681                                        .status(StatusCode::BAD_REQUEST)
682                                        .body(Body::from(format!("Couldn't parse path parameter value: {}", e)))
683                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
684                    },
685                    Err(_) => return Box::new(future::ok(Response::builder()
686                                        .status(StatusCode::BAD_REQUEST)
687                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["value"])))
688                                        .expect("Unable to create Bad Request response for invalid percent decode")))
689                };
690
691                Box::new({
692                        {{
693                                Box::new(
694                                    api_impl.i2c_bus_write_byte(
695                                            param_bus_id,
696                                            param_addr,
697                                            param_value,
698                                        &context
699                                    ).then(move |result| {
700                                        let mut response = Response::new(Body::empty());
701                                        response.headers_mut().insert(
702                                            HeaderName::from_static("x-span-id"),
703                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
704                                                .expect("Unable to create X-Span-ID header value"));
705
706                                        match result {
707                                            Ok(rsp) => match rsp {
708                                                I2cBusWriteByteResponse::OK
709                                                    (body)
710                                                => {
711                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
712                                                    response.headers_mut().insert(
713                                                        CONTENT_TYPE,
714                                                        HeaderValue::from_str("application/json")
715                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTE_OK"));
716                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
717                                                    *response.body_mut() = Body::from(body);
718                                                },
719                                                I2cBusWriteByteResponse::BadRequest
720                                                    (body)
721                                                => {
722                                                    *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode");
723                                                    response.headers_mut().insert(
724                                                        CONTENT_TYPE,
725                                                        HeaderValue::from_str("application/json")
726                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTE_BAD_REQUEST"));
727                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
728                                                    *response.body_mut() = Body::from(body);
729                                                },
730                                                I2cBusWriteByteResponse::TransactionFailed
731                                                    (body)
732                                                => {
733                                                    *response.status_mut() = StatusCode::from_u16(502).expect("Unable to turn 502 into a StatusCode");
734                                                    response.headers_mut().insert(
735                                                        CONTENT_TYPE,
736                                                        HeaderValue::from_str("application/json")
737                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTE_TRANSACTION_FAILED"));
738                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
739                                                    *response.body_mut() = Body::from(body);
740                                                },
741                                            },
742                                            Err(_) => {
743                                                // Application code returned an error. This should not happen, as the implementation should
744                                                // return a valid response.
745                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
746                                                *response.body_mut() = Body::from("An internal error occurred");
747                                            },
748                                        }
749
750                                        future::ok(response)
751                                    }
752                                ))
753                        }}
754                }) as Self::Future
755            },
756
757            // I2cBusWriteByteReg - POST /i2c/{busId}/write/byte/reg/{addr}/{reg}/{value}
758            &hyper::Method::POST if path.matched(paths::ID_I2C_BUSID_WRITE_BYTE_REG_ADDR_REG_VALUE) => {
759                // Path parameters
760                let path: &str = &uri.path().to_string();
761                let path_params =
762                    paths::REGEX_I2C_BUSID_WRITE_BYTE_REG_ADDR_REG_VALUE
763                    .captures(&path)
764                    .unwrap_or_else(||
765                        panic!("Path {} matched RE I2C_BUSID_WRITE_BYTE_REG_ADDR_REG_VALUE in set but failed match against \"{}\"", path, paths::REGEX_I2C_BUSID_WRITE_BYTE_REG_ADDR_REG_VALUE.as_str())
766                    );
767
768                let param_bus_id = match percent_encoding::percent_decode(path_params["busId"].as_bytes()).decode_utf8() {
769                    Ok(param_bus_id) => match param_bus_id.parse::<i32>() {
770                        Ok(param_bus_id) => param_bus_id,
771                        Err(e) => return Box::new(future::ok(Response::builder()
772                                        .status(StatusCode::BAD_REQUEST)
773                                        .body(Body::from(format!("Couldn't parse path parameter busId: {}", e)))
774                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
775                    },
776                    Err(_) => return Box::new(future::ok(Response::builder()
777                                        .status(StatusCode::BAD_REQUEST)
778                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["busId"])))
779                                        .expect("Unable to create Bad Request response for invalid percent decode")))
780                };
781
782                let param_addr = match percent_encoding::percent_decode(path_params["addr"].as_bytes()).decode_utf8() {
783                    Ok(param_addr) => match param_addr.parse::<i32>() {
784                        Ok(param_addr) => param_addr,
785                        Err(e) => return Box::new(future::ok(Response::builder()
786                                        .status(StatusCode::BAD_REQUEST)
787                                        .body(Body::from(format!("Couldn't parse path parameter addr: {}", e)))
788                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
789                    },
790                    Err(_) => return Box::new(future::ok(Response::builder()
791                                        .status(StatusCode::BAD_REQUEST)
792                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["addr"])))
793                                        .expect("Unable to create Bad Request response for invalid percent decode")))
794                };
795
796                let param_reg = match percent_encoding::percent_decode(path_params["reg"].as_bytes()).decode_utf8() {
797                    Ok(param_reg) => match param_reg.parse::<i32>() {
798                        Ok(param_reg) => param_reg,
799                        Err(e) => return Box::new(future::ok(Response::builder()
800                                        .status(StatusCode::BAD_REQUEST)
801                                        .body(Body::from(format!("Couldn't parse path parameter reg: {}", e)))
802                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
803                    },
804                    Err(_) => return Box::new(future::ok(Response::builder()
805                                        .status(StatusCode::BAD_REQUEST)
806                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["reg"])))
807                                        .expect("Unable to create Bad Request response for invalid percent decode")))
808                };
809
810                let param_value = match percent_encoding::percent_decode(path_params["value"].as_bytes()).decode_utf8() {
811                    Ok(param_value) => match param_value.parse::<i32>() {
812                        Ok(param_value) => param_value,
813                        Err(e) => return Box::new(future::ok(Response::builder()
814                                        .status(StatusCode::BAD_REQUEST)
815                                        .body(Body::from(format!("Couldn't parse path parameter value: {}", e)))
816                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
817                    },
818                    Err(_) => return Box::new(future::ok(Response::builder()
819                                        .status(StatusCode::BAD_REQUEST)
820                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["value"])))
821                                        .expect("Unable to create Bad Request response for invalid percent decode")))
822                };
823
824                Box::new({
825                        {{
826                                Box::new(
827                                    api_impl.i2c_bus_write_byte_reg(
828                                            param_bus_id,
829                                            param_addr,
830                                            param_reg,
831                                            param_value,
832                                        &context
833                                    ).then(move |result| {
834                                        let mut response = Response::new(Body::empty());
835                                        response.headers_mut().insert(
836                                            HeaderName::from_static("x-span-id"),
837                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
838                                                .expect("Unable to create X-Span-ID header value"));
839
840                                        match result {
841                                            Ok(rsp) => match rsp {
842                                                I2cBusWriteByteRegResponse::OK
843                                                    (body)
844                                                => {
845                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
846                                                    response.headers_mut().insert(
847                                                        CONTENT_TYPE,
848                                                        HeaderValue::from_str("application/json")
849                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTE_REG_OK"));
850                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
851                                                    *response.body_mut() = Body::from(body);
852                                                },
853                                                I2cBusWriteByteRegResponse::BadRequest
854                                                    (body)
855                                                => {
856                                                    *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode");
857                                                    response.headers_mut().insert(
858                                                        CONTENT_TYPE,
859                                                        HeaderValue::from_str("application/json")
860                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTE_REG_BAD_REQUEST"));
861                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
862                                                    *response.body_mut() = Body::from(body);
863                                                },
864                                                I2cBusWriteByteRegResponse::TransactionFailed
865                                                    (body)
866                                                => {
867                                                    *response.status_mut() = StatusCode::from_u16(502).expect("Unable to turn 502 into a StatusCode");
868                                                    response.headers_mut().insert(
869                                                        CONTENT_TYPE,
870                                                        HeaderValue::from_str("application/json")
871                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTE_REG_TRANSACTION_FAILED"));
872                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
873                                                    *response.body_mut() = Body::from(body);
874                                                },
875                                            },
876                                            Err(_) => {
877                                                // Application code returned an error. This should not happen, as the implementation should
878                                                // return a valid response.
879                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
880                                                *response.body_mut() = Body::from("An internal error occurred");
881                                            },
882                                        }
883
884                                        future::ok(response)
885                                    }
886                                ))
887                        }}
888                }) as Self::Future
889            },
890
891            // I2cBusWriteBytes - POST /i2c/{busId}/write/bytes/{addr}
892            &hyper::Method::POST if path.matched(paths::ID_I2C_BUSID_WRITE_BYTES_ADDR) => {
893                // Path parameters
894                let path: &str = &uri.path().to_string();
895                let path_params =
896                    paths::REGEX_I2C_BUSID_WRITE_BYTES_ADDR
897                    .captures(&path)
898                    .unwrap_or_else(||
899                        panic!("Path {} matched RE I2C_BUSID_WRITE_BYTES_ADDR in set but failed match against \"{}\"", path, paths::REGEX_I2C_BUSID_WRITE_BYTES_ADDR.as_str())
900                    );
901
902                let param_bus_id = match percent_encoding::percent_decode(path_params["busId"].as_bytes()).decode_utf8() {
903                    Ok(param_bus_id) => match param_bus_id.parse::<i32>() {
904                        Ok(param_bus_id) => param_bus_id,
905                        Err(e) => return Box::new(future::ok(Response::builder()
906                                        .status(StatusCode::BAD_REQUEST)
907                                        .body(Body::from(format!("Couldn't parse path parameter busId: {}", e)))
908                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
909                    },
910                    Err(_) => return Box::new(future::ok(Response::builder()
911                                        .status(StatusCode::BAD_REQUEST)
912                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["busId"])))
913                                        .expect("Unable to create Bad Request response for invalid percent decode")))
914                };
915
916                let param_addr = match percent_encoding::percent_decode(path_params["addr"].as_bytes()).decode_utf8() {
917                    Ok(param_addr) => match param_addr.parse::<i32>() {
918                        Ok(param_addr) => param_addr,
919                        Err(e) => return Box::new(future::ok(Response::builder()
920                                        .status(StatusCode::BAD_REQUEST)
921                                        .body(Body::from(format!("Couldn't parse path parameter addr: {}", e)))
922                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
923                    },
924                    Err(_) => return Box::new(future::ok(Response::builder()
925                                        .status(StatusCode::BAD_REQUEST)
926                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["addr"])))
927                                        .expect("Unable to create Bad Request response for invalid percent decode")))
928                };
929
930                // Body parameters (note that non-required body parameters will ignore garbage
931                // values, rather than causing a 400 response). Produce warning header and logs for
932                // any unused fields.
933                Box::new(body.concat2()
934                    .then(move |result| -> Self::Future {
935                        match result {
936                            Ok(body) => {
937                                let mut unused_elements = Vec::new();
938                                let param_values: Option<models::Values> = if !body.is_empty() {
939                                    let deserializer = &mut serde_json::Deserializer::from_slice(&*body);
940                                    match serde_ignored::deserialize(deserializer, |path| {
941                                            warn!("Ignoring unknown field in body: {}", path);
942                                            unused_elements.push(path.to_string());
943                                    }) {
944                                        Ok(param_values) => param_values,
945                                        Err(e) => return Box::new(future::ok(Response::builder()
946                                                        .status(StatusCode::BAD_REQUEST)
947                                                        .body(Body::from(format!("Couldn't parse body parameter Values - doesn't match schema: {}", e)))
948                                                        .expect("Unable to create Bad Request response for invalid body parameter Values due to schema"))),
949                                    }
950                                } else {
951                                    None
952                                };
953                                let param_values = match param_values {
954                                    Some(param_values) => param_values,
955                                    None => return Box::new(future::ok(Response::builder()
956                                                        .status(StatusCode::BAD_REQUEST)
957                                                        .body(Body::from("Missing required body parameter Values"))
958                                                        .expect("Unable to create Bad Request response for missing body parameter Values"))),
959                                };
960
961                                Box::new(
962                                    api_impl.i2c_bus_write_bytes(
963                                            param_bus_id,
964                                            param_addr,
965                                            param_values,
966                                        &context
967                                    ).then(move |result| {
968                                        let mut response = Response::new(Body::empty());
969                                        response.headers_mut().insert(
970                                            HeaderName::from_static("x-span-id"),
971                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
972                                                .expect("Unable to create X-Span-ID header value"));
973
974                                        if !unused_elements.is_empty() {
975                                            response.headers_mut().insert(
976                                                HeaderName::from_static("warning"),
977                                                HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str())
978                                                    .expect("Unable to create Warning header value"));
979                                        }
980
981                                        match result {
982                                            Ok(rsp) => match rsp {
983                                                I2cBusWriteBytesResponse::OK
984                                                    (body)
985                                                => {
986                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
987                                                    response.headers_mut().insert(
988                                                        CONTENT_TYPE,
989                                                        HeaderValue::from_str("application/json")
990                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTES_OK"));
991                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
992                                                    *response.body_mut() = Body::from(body);
993                                                },
994                                                I2cBusWriteBytesResponse::BadRequest
995                                                    (body)
996                                                => {
997                                                    *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode");
998                                                    response.headers_mut().insert(
999                                                        CONTENT_TYPE,
1000                                                        HeaderValue::from_str("application/json")
1001                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTES_BAD_REQUEST"));
1002                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
1003                                                    *response.body_mut() = Body::from(body);
1004                                                },
1005                                                I2cBusWriteBytesResponse::TransactionFailed
1006                                                    (body)
1007                                                => {
1008                                                    *response.status_mut() = StatusCode::from_u16(502).expect("Unable to turn 502 into a StatusCode");
1009                                                    response.headers_mut().insert(
1010                                                        CONTENT_TYPE,
1011                                                        HeaderValue::from_str("application/json")
1012                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTES_TRANSACTION_FAILED"));
1013                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
1014                                                    *response.body_mut() = Body::from(body);
1015                                                },
1016                                            },
1017                                            Err(_) => {
1018                                                // Application code returned an error. This should not happen, as the implementation should
1019                                                // return a valid response.
1020                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
1021                                                *response.body_mut() = Body::from("An internal error occurred");
1022                                            },
1023                                        }
1024
1025                                        future::ok(response)
1026                                    }
1027                                ))
1028                            },
1029                            Err(e) => Box::new(future::ok(Response::builder()
1030                                                .status(StatusCode::BAD_REQUEST)
1031                                                .body(Body::from(format!("Couldn't read body parameter Values: {}", e)))
1032                                                .expect("Unable to create Bad Request response due to unable to read body parameter Values"))),
1033                        }
1034                    })
1035                ) as Self::Future
1036            },
1037
1038            // I2cBusWriteBytesReg - POST /i2c/{busId}/write/bytes/reg/{addr}/{reg}
1039            &hyper::Method::POST if path.matched(paths::ID_I2C_BUSID_WRITE_BYTES_REG_ADDR_REG) => {
1040                // Path parameters
1041                let path: &str = &uri.path().to_string();
1042                let path_params =
1043                    paths::REGEX_I2C_BUSID_WRITE_BYTES_REG_ADDR_REG
1044                    .captures(&path)
1045                    .unwrap_or_else(||
1046                        panic!("Path {} matched RE I2C_BUSID_WRITE_BYTES_REG_ADDR_REG in set but failed match against \"{}\"", path, paths::REGEX_I2C_BUSID_WRITE_BYTES_REG_ADDR_REG.as_str())
1047                    );
1048
1049                let param_bus_id = match percent_encoding::percent_decode(path_params["busId"].as_bytes()).decode_utf8() {
1050                    Ok(param_bus_id) => match param_bus_id.parse::<i32>() {
1051                        Ok(param_bus_id) => param_bus_id,
1052                        Err(e) => return Box::new(future::ok(Response::builder()
1053                                        .status(StatusCode::BAD_REQUEST)
1054                                        .body(Body::from(format!("Couldn't parse path parameter busId: {}", e)))
1055                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
1056                    },
1057                    Err(_) => return Box::new(future::ok(Response::builder()
1058                                        .status(StatusCode::BAD_REQUEST)
1059                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["busId"])))
1060                                        .expect("Unable to create Bad Request response for invalid percent decode")))
1061                };
1062
1063                let param_addr = match percent_encoding::percent_decode(path_params["addr"].as_bytes()).decode_utf8() {
1064                    Ok(param_addr) => match param_addr.parse::<i32>() {
1065                        Ok(param_addr) => param_addr,
1066                        Err(e) => return Box::new(future::ok(Response::builder()
1067                                        .status(StatusCode::BAD_REQUEST)
1068                                        .body(Body::from(format!("Couldn't parse path parameter addr: {}", e)))
1069                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
1070                    },
1071                    Err(_) => return Box::new(future::ok(Response::builder()
1072                                        .status(StatusCode::BAD_REQUEST)
1073                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["addr"])))
1074                                        .expect("Unable to create Bad Request response for invalid percent decode")))
1075                };
1076
1077                let param_reg = match percent_encoding::percent_decode(path_params["reg"].as_bytes()).decode_utf8() {
1078                    Ok(param_reg) => match param_reg.parse::<i32>() {
1079                        Ok(param_reg) => param_reg,
1080                        Err(e) => return Box::new(future::ok(Response::builder()
1081                                        .status(StatusCode::BAD_REQUEST)
1082                                        .body(Body::from(format!("Couldn't parse path parameter reg: {}", e)))
1083                                        .expect("Unable to create Bad Request response for invalid path parameter"))),
1084                    },
1085                    Err(_) => return Box::new(future::ok(Response::builder()
1086                                        .status(StatusCode::BAD_REQUEST)
1087                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["reg"])))
1088                                        .expect("Unable to create Bad Request response for invalid percent decode")))
1089                };
1090
1091                // Body parameters (note that non-required body parameters will ignore garbage
1092                // values, rather than causing a 400 response). Produce warning header and logs for
1093                // any unused fields.
1094                Box::new(body.concat2()
1095                    .then(move |result| -> Self::Future {
1096                        match result {
1097                            Ok(body) => {
1098                                let mut unused_elements = Vec::new();
1099                                let param_values: Option<models::Values> = if !body.is_empty() {
1100                                    let deserializer = &mut serde_json::Deserializer::from_slice(&*body);
1101                                    match serde_ignored::deserialize(deserializer, |path| {
1102                                            warn!("Ignoring unknown field in body: {}", path);
1103                                            unused_elements.push(path.to_string());
1104                                    }) {
1105                                        Ok(param_values) => param_values,
1106                                        Err(e) => return Box::new(future::ok(Response::builder()
1107                                                        .status(StatusCode::BAD_REQUEST)
1108                                                        .body(Body::from(format!("Couldn't parse body parameter Values - doesn't match schema: {}", e)))
1109                                                        .expect("Unable to create Bad Request response for invalid body parameter Values due to schema"))),
1110                                    }
1111                                } else {
1112                                    None
1113                                };
1114                                let param_values = match param_values {
1115                                    Some(param_values) => param_values,
1116                                    None => return Box::new(future::ok(Response::builder()
1117                                                        .status(StatusCode::BAD_REQUEST)
1118                                                        .body(Body::from("Missing required body parameter Values"))
1119                                                        .expect("Unable to create Bad Request response for missing body parameter Values"))),
1120                                };
1121
1122                                Box::new(
1123                                    api_impl.i2c_bus_write_bytes_reg(
1124                                            param_bus_id,
1125                                            param_addr,
1126                                            param_reg,
1127                                            param_values,
1128                                        &context
1129                                    ).then(move |result| {
1130                                        let mut response = Response::new(Body::empty());
1131                                        response.headers_mut().insert(
1132                                            HeaderName::from_static("x-span-id"),
1133                                            HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
1134                                                .expect("Unable to create X-Span-ID header value"));
1135
1136                                        if !unused_elements.is_empty() {
1137                                            response.headers_mut().insert(
1138                                                HeaderName::from_static("warning"),
1139                                                HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str())
1140                                                    .expect("Unable to create Warning header value"));
1141                                        }
1142
1143                                        match result {
1144                                            Ok(rsp) => match rsp {
1145                                                I2cBusWriteBytesRegResponse::OK
1146                                                    (body)
1147                                                => {
1148                                                    *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
1149                                                    response.headers_mut().insert(
1150                                                        CONTENT_TYPE,
1151                                                        HeaderValue::from_str("application/json")
1152                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTES_REG_OK"));
1153                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
1154                                                    *response.body_mut() = Body::from(body);
1155                                                },
1156                                                I2cBusWriteBytesRegResponse::BadRequest
1157                                                    (body)
1158                                                => {
1159                                                    *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode");
1160                                                    response.headers_mut().insert(
1161                                                        CONTENT_TYPE,
1162                                                        HeaderValue::from_str("application/json")
1163                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTES_REG_BAD_REQUEST"));
1164                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
1165                                                    *response.body_mut() = Body::from(body);
1166                                                },
1167                                                I2cBusWriteBytesRegResponse::TransactionFailed
1168                                                    (body)
1169                                                => {
1170                                                    *response.status_mut() = StatusCode::from_u16(502).expect("Unable to turn 502 into a StatusCode");
1171                                                    response.headers_mut().insert(
1172                                                        CONTENT_TYPE,
1173                                                        HeaderValue::from_str("application/json")
1174                                                            .expect("Unable to create Content-Type header for I2C_BUS_WRITE_BYTES_REG_TRANSACTION_FAILED"));
1175                                                    let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
1176                                                    *response.body_mut() = Body::from(body);
1177                                                },
1178                                            },
1179                                            Err(_) => {
1180                                                // Application code returned an error. This should not happen, as the implementation should
1181                                                // return a valid response.
1182                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
1183                                                *response.body_mut() = Body::from("An internal error occurred");
1184                                            },
1185                                        }
1186
1187                                        future::ok(response)
1188                                    }
1189                                ))
1190                            },
1191                            Err(e) => Box::new(future::ok(Response::builder()
1192                                                .status(StatusCode::BAD_REQUEST)
1193                                                .body(Body::from(format!("Couldn't read body parameter Values: {}", e)))
1194                                                .expect("Unable to create Bad Request response due to unable to read body parameter Values"))),
1195                        }
1196                    })
1197                ) as Self::Future
1198            },
1199
1200            _ if path.matched(paths::ID_I2C_API) => method_not_allowed(),
1201            _ if path.matched(paths::ID_I2C_BUSLIST) => method_not_allowed(),
1202            _ if path.matched(paths::ID_I2C_BUSID_READ_BYTE_ADDR) => method_not_allowed(),
1203            _ if path.matched(paths::ID_I2C_BUSID_READ_BYTES_ADDR_NUMBYTES) => method_not_allowed(),
1204            _ if path.matched(paths::ID_I2C_BUSID_READ_REG_ADDR_REG_NUMBYTES) => method_not_allowed(),
1205            _ if path.matched(paths::ID_I2C_BUSID_WRITE_BYTE_REG_ADDR_REG_VALUE) => method_not_allowed(),
1206            _ if path.matched(paths::ID_I2C_BUSID_WRITE_BYTE_ADDR_VALUE) => method_not_allowed(),
1207            _ if path.matched(paths::ID_I2C_BUSID_WRITE_BYTES_REG_ADDR_REG) => method_not_allowed(),
1208            _ if path.matched(paths::ID_I2C_BUSID_WRITE_BYTES_ADDR) => method_not_allowed(),
1209            _ => Box::new(future::ok(
1210                Response::builder().status(StatusCode::NOT_FOUND)
1211                    .body(Body::empty())
1212                    .expect("Unable to create Not Found response")
1213            )) as Self::Future
1214        }
1215    }
1216}
1217
1218impl<T, C> Clone for Service<T, C> where T: Clone
1219{
1220    fn clone(&self) -> Self {
1221        Service {
1222            api_impl: self.api_impl.clone(),
1223            marker: self.marker.clone(),
1224        }
1225    }
1226}
1227
1228/// Request parser for `Api`.
1229pub struct ApiRequestParser;
1230impl<T> RequestParser<T> for ApiRequestParser {
1231    fn parse_operation_id(request: &Request<T>) -> Result<&'static str, ()> {
1232        let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path());
1233        match request.method() {
1234            // I2cBusApi - GET /i2c/api
1235            &hyper::Method::GET if path.matched(paths::ID_I2C_API) => Ok("I2cBusApi"),
1236            // I2cBusList - GET /i2c/buslist
1237            &hyper::Method::GET if path.matched(paths::ID_I2C_BUSLIST) => Ok("I2cBusList"),
1238            // I2cBusReadByte - GET /i2c/{busId}/read/byte/{addr}
1239            &hyper::Method::GET if path.matched(paths::ID_I2C_BUSID_READ_BYTE_ADDR) => Ok("I2cBusReadByte"),
1240            // I2cBusReadBytes - GET /i2c/{busId}/read/bytes/{addr}/{numBytes}
1241            &hyper::Method::GET if path.matched(paths::ID_I2C_BUSID_READ_BYTES_ADDR_NUMBYTES) => Ok("I2cBusReadBytes"),
1242            // I2cBusReadReg - GET /i2c/{busId}/read/reg/{addr}/{reg}/{numBytes}
1243            &hyper::Method::GET if path.matched(paths::ID_I2C_BUSID_READ_REG_ADDR_REG_NUMBYTES) => Ok("I2cBusReadReg"),
1244            // I2cBusWriteByte - POST /i2c/{busId}/write/byte/{addr}/{value}
1245            &hyper::Method::POST if path.matched(paths::ID_I2C_BUSID_WRITE_BYTE_ADDR_VALUE) => Ok("I2cBusWriteByte"),
1246            // I2cBusWriteByteReg - POST /i2c/{busId}/write/byte/reg/{addr}/{reg}/{value}
1247            &hyper::Method::POST if path.matched(paths::ID_I2C_BUSID_WRITE_BYTE_REG_ADDR_REG_VALUE) => Ok("I2cBusWriteByteReg"),
1248            // I2cBusWriteBytes - POST /i2c/{busId}/write/bytes/{addr}
1249            &hyper::Method::POST if path.matched(paths::ID_I2C_BUSID_WRITE_BYTES_ADDR) => Ok("I2cBusWriteBytes"),
1250            // I2cBusWriteBytesReg - POST /i2c/{busId}/write/bytes/reg/{addr}/{reg}
1251            &hyper::Method::POST if path.matched(paths::ID_I2C_BUSID_WRITE_BYTES_REG_ADDR_REG) => Ok("I2cBusWriteBytesReg"),
1252            _ => Err(()),
1253        }
1254    }
1255}