Skip to content
MEC application.ipynb 272 KiB
Newer Older
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433
    "    Stop the notification server\n",
    "    :param The instance of the HTTP server\n",
    "    \"\"\"\n",
    "    httpd.server_close()\n",
    "    httpd=None\n",
    "    # End of function HTTPRequestHandler\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "def subscribe_for_user_events(sandbox_name: str) -> object:\n",
    "    \"\"\"\n",
    "    Subscriptions for notifications related to location.\n",
    "    :param sandbox_name: The MEC Sandbox instance to use\n",
    "    :return: The HTTP respone, the subscription ID and the resource URL on success, None otherwise\n",
    "    :see ETSI GS MEC 013 V3.1.1 Clause 7.5 Resource: user_subscriptions\n",
    "    \"\"\"\n",
    "    global MEC_PLTF, logger, service_api\n",
    "\n",
    "    logger.debug('>>> subscribe_for_user_events: ' + sandbox_name)\n",
    "    try:\n",
    "        url = '/{sandbox_name}/{mec_pltf}//location/v3/subscriptions/users'\n",
    "        logger.debug('subscribe_for_user_events: url: ' + url)\n",
    "        path_params = {}\n",
    "        path_params['sandbox_name'] = sandbox_name\n",
    "        path_params['mec_pltf'] = MEC_PLTF\n",
    "        header_params = {}\n",
    "        # HTTP header `Accept`\n",
    "        header_params['Accept'] = 'application/json'  # noqa: E501\n",
    "        # HTTP header `Content-Type`\n",
    "        header_params['Content-Type'] = 'application/json'  # noqa: E501\n",
    "        # Body\n",
    "        dict_body = {}\n",
    "        dict_body['subscriptionType'] = 'UserLocationEventSubscription'\n",
    "        dict_body['callbackReference'] = CALLBACK_URI + '/mec013/v3/location' # FIXME To be parameterized\n",
    "        dict_body['address'] = '10.100.0.1' # FIXME To be parameterized\n",
    "        dict_body['clientCorrelator'] = \"12345\"\n",
    "        dict_body['locationEventCriteria'] = [ \"ENTERING_AREA_EVENT\", \"LEAVING_AREA_EVENT\"]\n",
    "        m = {}\n",
    "        m[\"userLocationEventSubscription\"] = dict_body\n",
    "        (result, status, headers) = service_api.call_api(url, 'POST', header_params=header_params, path_params = path_params, body=m, async_req=False)\n",
    "        return (result, extract_sub_id(headers['Location']), headers['Location'])\n",
    "    except ApiException as e:\n",
    "        logger.error('Exception when calling call_api: %s\\n' % e)\n",
    "    return None\n",
    "    # End of function subscribe_for_user_are_event"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Putting everything together\n",
    "\n",
    "It is time now to create the our third iteration of our MEC application.\n",
    "\n",
    "The sequence is the following:\n",
    "- Login\n",
    "- Activate a network scenario\n",
    "- Create subscription\n",
    "- Wait for notification\n",
    "- Delete our application instance identifier\n",
    "- Deactivate a network scenario\n",
    "- Logout"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-12 13:26:28,384 - __main__ - DEBUG - Starting at 20241112-132628\n",
      "2024-11-12 13:26:28,385 - __main__ - DEBUG - \t pwd= /home/jovyan/work/mecapp\n",
      "2024-11-12 13:26:28,388 - __main__ - DEBUG - >>> process_login\n",
      "2024-11-12 13:26:28,390 DEBUG Resetting dropped connection: mec-platform2.etsi.org\n",
      "2024-11-12 13:26:28,457 DEBUG https://mec-platform2.etsi.org:443 \"POST /sandbox-api/v1/login?provider=Jupyter2024 HTTP/11\" 201 0\n",
      "2024-11-12 13:26:28,463 DEBUG response body: b'{\"user_code\":\"sbxlm5h1yu\",\"verification_uri\":\"\"}'\n",
      "2024-11-12 13:26:28,464 - __main__ - DEBUG - process_login (step1): oauth: {'user_code': 'sbxlm5h1yu', 'verification_uri': ''}\n",
      "2024-11-12 13:26:28,465 - __main__ - DEBUG - =======================> DO AUTHORIZATION WITH CODE : sbxlm5h1yu\n",
      "2024-11-12 13:26:28,466 - __main__ - DEBUG - =======================> DO AUTHORIZATION HERE :      \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "send: b'POST /sandbox-api/v1/login?provider=Jupyter2024 HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nContent-Length: 2\\r\\nAccept: application/json\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "send: b'{}'\n",
      "reply: 'HTTP/1.1 201 Created\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:26:28 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Content-Length: 48\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-12 13:26:31,477 DEBUG https://mec-platform2.etsi.org:443 \"GET /sandbox-api/v1/namespace?user_code=sbxlm5h1yu HTTP/11\" 200 0\n",
      "2024-11-12 13:26:31,478 DEBUG response body: b'{\"sandbox_name\":\"sbxlm5h1yu\"}'\n",
      "2024-11-12 13:26:31,479 - __main__ - DEBUG - process_login (step2): result: {'sandbox_name': 'sbxlm5h1yu'}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "send: b'GET /sandbox-api/v1/namespace?user_code=sbxlm5h1yu HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nAccept: application/json\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "reply: 'HTTP/1.1 200 OK\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:26:31 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Content-Length: 29\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-12 13:26:41,481 - __main__ - DEBUG - >>> get_network_scenarios: sandbox=sbxlm5h1yu\n",
      "2024-11-12 13:26:41,483 DEBUG Resetting dropped connection: mec-platform2.etsi.org\n",
      "2024-11-12 13:26:41,566 DEBUG https://mec-platform2.etsi.org:443 \"GET /sandbox-api/v1/sandboxNetworkScenarios?sandbox_name=sbxlm5h1yu HTTP/11\" 200 0\n",
      "2024-11-12 13:26:41,568 DEBUG response body: b'[{\"id\":\"4g-5g-macro-v2x\"},{\"id\":\"4g-5g-macro-v2x-fed\"},{\"id\":\"4g-5g-wifi-macro\"},{\"id\":\"4g-macro\"},{\"id\":\"4g-wifi-macro\"},{\"id\":\"dual-mep-4g-5g-wifi-macro\"},{\"id\":\"dual-mep-short-path\"}]'\n",
      "2024-11-12 13:26:41,568 - __main__ - DEBUG - get_network_scenarios: result: [{'id': '4g-5g-macro-v2x'}, {'id': '4g-5g-macro-v2x-fed'}, {'id': '4g-5g-wifi-macro'}, {'id': '4g-macro'}, {'id': '4g-wifi-macro'}, {'id': 'dual-mep-4g-5g-wifi-macro'}, {'id': 'dual-mep-short-path'}]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "send: b'GET /sandbox-api/v1/sandboxNetworkScenarios?sandbox_name=sbxlm5h1yu HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nAccept: application/json\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "reply: 'HTTP/1.1 200 OK\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:26:41 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Content-Length: 186\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-12 13:26:51,569 - __main__ - DEBUG - >>> activate_network_scenario: sbxlm5h1yu\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "send: b'POST /sandbox-api/v1/sandboxNetworkScenarios/sbxlm5h1yu?network_scenario_id=4g-5g-macro-v2x HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nContent-Length: 2\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "send: b'{}'\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-12 13:26:53,000 DEBUG https://mec-platform2.etsi.org:443 \"POST /sandbox-api/v1/sandboxNetworkScenarios/sbxlm5h1yu?network_scenario_id=4g-5g-macro-v2x HTTP/11\" 204 0\n",
      "2024-11-12 13:26:53,006 DEBUG response body: b''\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "reply: 'HTTP/1.1 204 No Content\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:26:52 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-12 13:27:13,007 - __main__ - DEBUG - >>> request_application_instance_id: sbxlm5h1yu\n",
      "2024-11-12 13:27:13,009 DEBUG Resetting dropped connection: mec-platform2.etsi.org\n",
      "2024-11-12 13:27:13,101 DEBUG https://mec-platform2.etsi.org:443 \"POST /sandbox-api/v1/sandboxAppInstances/sbxlm5h1yu HTTP/11\" 201 0\n",
      "2024-11-12 13:27:13,102 DEBUG response body: b'{\"id\":\"546415bd-46a0-459c-a5da-1fd80b2719e5\",\"name\":\"JupyterMecApp\",\"nodeName\":\"mep1\",\"type\":\"USER\"}'\n",
      "2024-11-12 13:27:13,104 - __main__ - DEBUG - request_application_instance_id: result: {'id': '546415bd-46a0-459c-a5da-1fd80b2719e5',\n",
      " 'name': 'JupyterMecApp',\n",
      " 'node_name': 'mep1',\n",
      " 'persist': None,\n",
      " 'type': 'USER'}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "send: b'POST /sandbox-api/v1/sandboxAppInstances/sbxlm5h1yu HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nContent-Length: 107\\r\\nAccept: application/json\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "send: b'{\"id\": \"546415bd-46a0-459c-a5da-1fd80b2719e5\", \"name\": \"JupyterMecApp\", \"nodeName\": \"mep1\", \"type\": \"USER\"}'\n",
      "reply: 'HTTP/1.1 201 Created\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:27:13 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Content-Length: 100\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-12 13:27:23,105 - __main__ - DEBUG - >>> send_ready_confirmation: 546415bd-46a0-459c-a5da-1fd80b2719e5\n",
      "2024-11-12 13:27:23,106 - __main__ - DEBUG - send_ready_confirmation: url: /{sandbox_name}/{mec_pltf}/mec_app_support/v2/applications/{app_inst_id}/confirm_ready\n",
      "2024-11-12 13:27:23,107 DEBUG Resetting dropped connection: mec-platform2.etsi.org\n",
      "2024-11-12 13:27:23,156 DEBUG https://mec-platform2.etsi.org:443 \"POST /sbxlm5h1yu/mep1/mec_app_support/v2/applications/546415bd-46a0-459c-a5da-1fd80b2719e5/confirm_ready HTTP/11\" 204 0\n",
      "2024-11-12 13:27:23,159 DEBUG response body: b''\n",
      "2024-11-12 13:27:23,160 - __main__ - DEBUG - >>> send_subscribe_termination: 546415bd-46a0-459c-a5da-1fd80b2719e5\n",
      "2024-11-12 13:27:23,166 - __main__ - DEBUG - send_subscribe_termination: url: /{sandbox_name}/{mec_pltf}/mec_app_support/v2/applications/{app_inst_id}/subscriptions\n",
      "2024-11-12 13:27:23,171 DEBUG https://mec-platform2.etsi.org:443 \"POST /sbxlm5h1yu/mep1/mec_app_support/v2/applications/546415bd-46a0-459c-a5da-1fd80b2719e5/subscriptions HTTP/11\" 201 0\n",
      "2024-11-12 13:27:23,173 DEBUG response body: b'{\"subscriptionType\":\"AppTerminationNotificationSubscription\",\"callbackReference\":\"http://mec-platform2.etsi.org:31111/sandbox/v1/mec011/v2/termination\",\"_links\":{\"self\":{\"href\":\"https://mec-platform2.etsi.org/sbxlm5h1yu/mep1/mec_app_support/v2/applications/546415bd-46a0-459c-a5da-1fd80b2719e5/subscriptions/sub-LtLIjh4RP1-aiUeZ\"}},\"appInstanceId\":\"546415bd-46a0-459c-a5da-1fd80b2719e5\"}'\n",
      "2024-11-12 13:27:23,175 - __main__ - DEBUG - >>> extract_sub_id: resource_url: https://mec-platform2.etsi.org/sbxlm5h1yu/mep1/mec_app_support/v2/applications/546415bd-46a0-459c-a5da-1fd80b2719e5/subscriptions/sub-LtLIjh4RP1-aiUeZ\n",
      "2024-11-12 13:27:23,176 - __main__ - DEBUG - >>> subscribe_for_user_events: sbxlm5h1yu\n",
      "2024-11-12 13:27:23,177 - __main__ - DEBUG - subscribe_for_user_events: url: /{sandbox_name}/{mec_pltf}//location/v3/subscriptions/users\n",
      "2024-11-12 13:27:23,184 DEBUG https://mec-platform2.etsi.org:443 \"POST /sbxlm5h1yu/mep1//location/v3/subscriptions/users HTTP/11\" 201 0\n",
      "2024-11-12 13:27:23,185 DEBUG response body: b'{\"userLocationEventSubscription\":{\"_links\":{\"self\":{\"href\":\"https://mec-platform2.etsi.org/sbxlm5h1yu/mep1/location/v3/subscriptions/users/2\"}},\"address\":\"10.100.0.1\",\"callbackReference\":\"http://mec-platform2.etsi.org:31111/sandbox/v1/mec013/v3/location\",\"clientCorrelator\":\"12345\",\"locationEventCriteria\":[\"ENTERING_AREA_EVENT\",\"LEAVING_AREA_EVENT\"],\"subscriptionType\":\"UserLocationEventSubscription\"}}'\n",
      "2024-11-12 13:27:23,186 - __main__ - DEBUG - >>> extract_sub_id: resource_url: https://mec-platform2.etsi.org/sbxlm5h1yu/mep1/location/v3/subscriptions/users/2\n",
      "2024-11-12 13:27:23,188 - __main__ - INFO - UE location information: status: 2\n",
      "2024-11-12 13:27:23,188 - __main__ - ERROR - Failed to get UE location information\n",
      "2024-11-12 13:27:23,203 - __main__ - DEBUG - >>> get_ue_location: 10.100.0.1\n",
      "2024-11-12 13:27:23,207 - __main__ - DEBUG - get_ue_location: url: /{sandbox_name}/{mec_pltf}/location/v3/queries/users\n",
      "2024-11-12 13:27:23,220 DEBUG https://mec-platform2.etsi.org:443 \"GET /sbxlm5h1yu/mep1/location/v3/queries/users?address=10.100.0.1 HTTP/11\" 200 0\n",
      "2024-11-12 13:27:23,221 DEBUG response body: b'{\"userList\":{\"resourceURL\":\"https://mec-platform2.etsi.org/sbxlm5h1yu/mep1/location/v3/queries/users\",\"user\":[{\"address\":\"10.100.0.1\",\"accessPointId\":\"5g-small-cell-2\",\"zoneId\":\"zone01\",\"resourceURL\":\"https://mec-platform2.etsi.org/sbxlm5h1yu/mep1/location/v3/queries/users?address=10.100.0.1\",\"timestamp\":{\"nanoSeconds\":0,\"seconds\":1731418042},\"locationInfo\":{\"latitude\":[43.73147],\"longitude\":[7.417372],\"shape\":2},\"civicInfo\":{\"country\":\"MC\"},\"relativeLocationInfo\":{\"X\":7.594824,\"Y\":-314.42572,\"mapInfo\":{\"mapId\":\"324561243\",\"origin\":{\"latitude\":43.7314,\"longitude\":7.4202}}}}]}}'\n",
      "2024-11-12 13:27:23,222 - __main__ - INFO - UE location information: status: 200\n",
      "2024-11-12 13:27:23,222 - __main__ - INFO - UE location information: b'{\"userList\":{\"resourceURL\":\"https://mec-platform2.etsi.org/sbxlm5h1yu/mep1/location/v3/queries/users\",\"user\":[{\"address\":\"10.100.0.1\",\"accessPointId\":\"5g-small-cell-2\",\"zoneId\":\"zone01\",\"resourceURL\":\"https://mec-platform2.etsi.org/sbxlm5h1yu/mep1/location/v3/queries/users?address=10.100.0.1\",\"timestamp\":{\"nanoSeconds\":0,\"seconds\":1731418042},\"locationInfo\":{\"latitude\":[43.73147],\"longitude\":[7.417372],\"shape\":2},\"civicInfo\":{\"country\":\"MC\"},\"relativeLocationInfo\":{\"X\":7.594824,\"Y\":-314.42572,\"mapInfo\":{\"mapId\":\"324561243\",\"origin\":{\"latitude\":43.7314,\"longitude\":7.4202}}}}]}}'\n",
      "2024-11-12 13:27:23,223 - __main__ - INFO - Waiting for subscription...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "send: b'POST /sbxlm5h1yu/mep1/mec_app_support/v2/applications/546415bd-46a0-459c-a5da-1fd80b2719e5/confirm_ready HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nContent-Length: 23\\r\\nAccept: application/json\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "send: b'{\"indication\": \"READY\"}'\n",
      "reply: 'HTTP/1.1 204 No Content\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:27:23 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n",
      "send: b'POST /sbxlm5h1yu/mep1/mec_app_support/v2/applications/546415bd-46a0-459c-a5da-1fd80b2719e5/subscriptions HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nContent-Length: 212\\r\\nAccept: application/json\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "send: b'{\"subscriptionType\": \"AppTerminationNotificationSubscription\", \"callbackReference\": \"http://mec-platform2.etsi.org:31111/sandbox/v1/mec011/v2/termination\", \"appInstanceId\": \"546415bd-46a0-459c-a5da-1fd80b2719e5\"}'\n",
      "reply: 'HTTP/1.1 201 Created\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:27:23 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Content-Length: 387\n",
      "header: Connection: keep-alive\n",
      "header: Location: https://mec-platform2.etsi.org/sbxlm5h1yu/mep1/mec_app_support/v2/applications/546415bd-46a0-459c-a5da-1fd80b2719e5/subscriptions/sub-LtLIjh4RP1-aiUeZ\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n",
      "send: b'POST /sbxlm5h1yu/mep1//location/v3/subscriptions/users HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nContent-Length: 304\\r\\nAccept: application/json\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "send: b'{\"userLocationEventSubscription\": {\"subscriptionType\": \"UserLocationEventSubscription\", \"callbackReference\": \"http://mec-platform2.etsi.org:31111/sandbox/v1/mec013/v3/location\", \"address\": \"10.100.0.1\", \"clientCorrelator\": \"12345\", \"locationEventCriteria\": [\"ENTERING_AREA_EVENT\", \"LEAVING_AREA_EVENT\"]}}'\n",
      "reply: 'HTTP/1.1 201 Created\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:27:23 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Content-Length: 403\n",
      "header: Connection: keep-alive\n",
      "header: Location: https://mec-platform2.etsi.org/sbxlm5h1yu/mep1/location/v3/subscriptions/users/2\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n",
      "send: b'GET /sbxlm5h1yu/mep1/location/v3/queries/users?address=10.100.0.1 HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nAccept: application/json\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "reply: 'HTTP/1.1 200 OK\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:27:23 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Content-Length: 583\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-12 13:27:33,223 - __main__ - INFO - Waiting for subscription...\n",
      "2024-11-12 13:27:43,224 - __main__ - INFO - Waiting for subscription...\n",
      "2024-11-12 13:27:53,225 - __main__ - INFO - Waiting for subscription...\n",
      "2024-11-12 13:28:03,227 - __main__ - INFO - Waiting for subscription...\n",
      "2024-11-12 13:28:13,228 - __main__ - INFO - Waiting for subscription...\n",
      "2024-11-12 13:28:23,229 - __main__ - INFO - Waiting for subscription...\n",
      "2024-11-12 13:28:33,231 - __main__ - INFO - Waiting for subscription...\n",
      "2024-11-12 13:28:43,232 - __main__ - INFO - Waiting for subscription...\n",
      "2024-11-12 13:28:53,233 - __main__ - INFO - Waiting for subscription...\n",
      "2024-11-12 13:29:03,234 - __main__ - DEBUG - >>> delete_subscribe_termination: 546415bd-46a0-459c-a5da-1fd80b2719e5\n",
      "2024-11-12 13:29:03,235 - __main__ - DEBUG - delete_subscribe_termination: url: /{sandbox_name}/{mec_pltf}/mec_app_support/v2/applications/{app_inst_id}/subscriptions/{sub_id}\n",
      "2024-11-12 13:29:03,235 DEBUG Resetting dropped connection: mec-platform2.etsi.org\n",
      "2024-11-12 13:29:03,270 DEBUG https://mec-platform2.etsi.org:443 \"DELETE /sbxlm5h1yu/mep1/mec_app_support/v2/applications/546415bd-46a0-459c-a5da-1fd80b2719e5/subscriptions/sub-LtLIjh4RP1-aiUeZ HTTP/11\" 204 0\n",
      "2024-11-12 13:29:03,272 DEBUG response body: b''\n",
      "2024-11-12 13:29:03,273 - __main__ - DEBUG - >>> delete_application_instance_id: sbxlm5h1yu\n",
      "2024-11-12 13:29:03,274 - __main__ - DEBUG - >>> delete_application_instance_id: 546415bd-46a0-459c-a5da-1fd80b2719e5\n",
      "2024-11-12 13:29:03,275 DEBUG Resetting dropped connection: mec-platform2.etsi.org\n",
      "2024-11-12 13:29:03,415 DEBUG https://mec-platform2.etsi.org:443 \"DELETE /sandbox-api/v1/sandboxAppInstances/sbxlm5h1yu/546415bd-46a0-459c-a5da-1fd80b2719e5 HTTP/11\" 204 0\n",
      "2024-11-12 13:29:03,416 DEBUG response body: b''\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "send: b'DELETE /sbxlm5h1yu/mep1/mec_app_support/v2/applications/546415bd-46a0-459c-a5da-1fd80b2719e5/subscriptions/sub-LtLIjh4RP1-aiUeZ HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nContent-Length: 2\\r\\nAccept: application/json\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "send: b'{}'\n",
      "reply: 'HTTP/1.1 204 No Content\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:29:03 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n",
      "send: b'DELETE /sandbox-api/v1/sandboxAppInstances/sbxlm5h1yu/546415bd-46a0-459c-a5da-1fd80b2719e5 HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nContent-Length: 2\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "send: b'{}'\n",
      "reply: 'HTTP/1.1 204 No Content\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:29:03 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-12 13:29:13,417 - __main__ - DEBUG - >>> deactivate_network_scenario: sbxlm5h1yu\n",
      "2024-11-12 13:29:13,445 DEBUG https://mec-platform2.etsi.org:443 \"DELETE /sandbox-api/v1/sandboxNetworkScenarios/sbxlm5h1yu/4g-5g-macro-v2x HTTP/11\" 204 0\n",
      "2024-11-12 13:29:13,447 DEBUG response body: b''\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "send: b'DELETE /sandbox-api/v1/sandboxNetworkScenarios/sbxlm5h1yu/4g-5g-macro-v2x HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nContent-Length: 2\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "send: b'{}'\n",
      "reply: 'HTTP/1.1 204 No Content\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:29:13 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-12 13:29:33,451 - __main__ - DEBUG - >>> process_logout: sandbox=sbxlm5h1yu\n",
      "2024-11-12 13:29:33,452 DEBUG Resetting dropped connection: mec-platform2.etsi.org\n",
      "2024-11-12 13:29:33,560 DEBUG https://mec-platform2.etsi.org:443 \"POST /sandbox-api/v1/logout?sandbox_name=sbxlm5h1yu HTTP/11\" 204 0\n",
      "2024-11-12 13:29:33,562 DEBUG response body: b''\n",
      "2024-11-12 13:29:33,563 - __main__ - DEBUG - Stopped at 20241112-132933\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "send: b'POST /sandbox-api/v1/logout?sandbox_name=sbxlm5h1yu HTTP/1.1\\r\\nHost: mec-platform2.etsi.org\\r\\nAccept-Encoding: identity\\r\\nContent-Length: 2\\r\\nContent-Type: application/json\\r\\nUser-Agent: Swagger-Codegen/1.0.0/python\\r\\n\\r\\n'\n",
      "send: b'{}'\n",
      "reply: 'HTTP/1.1 204 No Content\\r\\n'\n",
      "header: Date: Tue, 12 Nov 2024 13:29:33 GMT\n",
      "header: Content-Type: application/json; charset=UTF-8\n",
      "header: Connection: keep-alive\n",
      "header: Strict-Transport-Security: max-age=15724800; includeSubDomains\n"
     ]
    }
   ],
   "source": [
    "def process_main():\n",
    "    \"\"\"\n",
    "    This is the second sprint of our skeleton of our MEC application:\n",
    "        - Login\n",
    "        - Activate a network scenario\n",
    "        - Create subscription\n",
    "        - Wait for notification\n",
    "        - Delete our application instance identifier\n",
    "        - Deactivate a network scenario\n",
    "        - Logout\n",
    "    \"\"\" \n",
    "    global logger, nw_scenarios, got_notification\n",
    "\n",
    "    logger.debug('Starting at ' + time.strftime('%Y%m%d-%H%M%S'))\n",
    "    logger.debug('\\t pwd= ' + os.getcwd())\n",
    "\n",
    "    # Start notification server in a daemonized thread\n",
    "    httpd = start_notification_server()\n",
    "\n",
    "    # Setup the MEC application\n",
    "    (sandbox_name, app_inst_id, sub_id) = mec_app_setup()\n",
    "\n",
    "    # Create subscription\n",
    "    result, status, headers = subscribe_for_user_events(sandbox_name)\n",
    "    logger.info('UE location information: status: %s', str(status))\n",
    "    if status != 200:\n",
    "        logger.error('Failed to get UE location information')\n",
    "    else:\n",
    "        logger.info('UE location information: ' + str(result.data))\n",
    "    \n",
    "    # Getting UE location lookup\n",
    "    result, status = get_ue_location(sandbox_name, '10.100.0.1')\n",
    "    logger.info('UE location information: status: ' + str(status))\n",
    "    if status != 200:\n",
    "        logger.error('Failed to get UE location information')\n",
    "    else:\n",
    "        logger.info('UE location information: ' + str(result.data))\n",
    "\n",
    "    # Wait for the notification\n",
    "    counter = 0\n",
    "    while not got_notification and counter < 30:\n",
    "        logger.info('Waiting for subscription...')\n",
    "        time.sleep(STABLE_TIME_OUT)\n",
    "        counter += 1\n",
    "        # End of 'while' statement\n",
    "\n",
    "    # Stop notification server\n",
    "    stop_notification_server(httpd)\n",
    "\n",
    "    # Terminate the MEC application\n",
    "    mec_app_termination(sandbox_name, app_inst_id, sub_id)\n",
    "\n",
    "    logger.debug('Stopped at ' + time.strftime('%Y%m%d-%H%M%S'))\n",
    "    # End of function process_main\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    process_main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create our third MEC application: how to use V2X MEC Services\n",
    "After doing the logging, network scenario activation, MEC application instance creation steps, we are ready to exploit the MEC services exposed by the MEC Sandbox.\n",
    "\n",
    "In this clause, we use the following functionalities provided by MEC-030:\n",
    "- Getting UU unicast provisioning information (ETSI GS MEC 030 Clause 5.5.1)\n",
    "- Subscribe to the V2X message distribution server (ETSI GS MEC 030 Clause 5.5.7)\n",
    "- Delete subscription\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Getting UU unicast provisioning information\n",
    "\n",
    "The purpose is to query provisioning information for V2X communication over Uu unicast."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
Yann Garcia's avatar
Yann Garcia committed
    "def send_uu_unicast_provisioning_info(sandbox_name: str, ecgi: str) -> object:\n",
    "    \"\"\"\n",
    "    Request for V2X communication over Uu unicast information\n",
    "    :param sandbox_name: The MEC Sandbox instance to use\n",
    "    :param ecgi: Comma separated list of locations to identify a cell of a base station or a particular geographical area\n",
    "    :return The Uu unicast provisioning information on success, None otherwise\n",
    "    :see ETSI GS MEC 030 V3.2.1 (2024-02) Clause 5.5.1 Sending a request for provisioning information for V2X communication over Uu unicast\n",
    "    \"\"\"\n",
    "    global MEC_PLTF, logger, service_api\n",
    "    logger.debug('>>> send_uu_unicast_provisioning_info: ' + ecgi)\n",
    "        url = '/{sandbox_name}/{mec_pltf}/vis/v2/queries/uu_unicast_provisioning_info'\n",
    "        logger.debug('send_uu_unicast_provisioning_info: url: ' + url)\n",
    "        path_params = {}\n",
    "        path_params['sandbox_name'] = sandbox_name\n",
    "        path_params['mec_pltf'] = MEC_PLTF\n",
    "        query_params = []\n",
    "        query_params.append(('location_info', 'ecgi,' + ecgi))\n",
    "        header_params = {}\n",
    "        # HTTP header `Accept`\n",
    "        header_params['Accept'] = 'application/json'  # noqa: E501\n",
    "        # HTTP header `Content-Type`\n",
    "        header_params['Content-Type'] = 'application/json'  # noqa: E501\n",
Yann Garcia's avatar
Yann Garcia committed
    "        (result, status, header) = service_api.call_api(url, 'GET', header_params=header_params, path_params=path_params, query_params=query_params, async_req=False)\n",
    "        return (result, status, header)\n",
    "    except ApiException as e:\n",
    "        logger.error('Exception when calling call_api: %s\\n' % e)\n",
    "    # End of function send_uu_unicast_provisioning_info"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's create the our second MEC application.\n",
    "The sequence is the following:\n",
    "- Mec application setup\n",
    "- Get UU unicast provisioning information\n",
    "- Mec application termination\n",
    "\n",
    "Note that the UU unicast provisioning information is returned as a JSON string. To de-serialized it into a Python data structure, please refer to clause [Subscribing to V2X message distribution server](#subscribing_to_v2x_message_distribution_server)."
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Putting everything together"
   ]
  },
   "cell_type": "code",
Yann Garcia's avatar
Yann Garcia committed
   "source": [
    "def process_main():\n",
    "    \"\"\"\n",
    "    This is the second sprint of our skeleton of our MEC application:\n",
    "        - Mec application setup\n",
    "        - Get UU unicast provisioning information\n",
    "        - Mec application termination\n",
    "    \"\"\" \n",
    "    global logger, nw_scenarios\n",
    "\n",
    "    logger.debug('Starting at ' + time.strftime('%Y%m%d-%H%M%S'))\n",
    "    logger.debug('\\t pwd= ' + os.getcwd())\n",
    "\n",
    "    # Setup the MEC application\n",
    "    (sandbox_name, app_inst_id, sub_id) = mec_app_setup()\n",
    "\n",
    "    # Get UU unicast provisioning information\n",
    "    ecgi = \"268708941961,268711972264\" # List of ecgi spearated by a ','\n",
    "    result, status, header = send_uu_unicast_provisioning_info(sandbox_name, ecgi)\n",
    "    logger.info('UU unicast provisioning information: status: %s', str(status))\n",
    "    if status != 200:\n",
    "        logger.error('Failed to get UU unicast provisioning information')\n",
    "    else:\n",
    "        logger.info('UU unicast provisioning information: %s', str(result.data))\n",
    "\n",
    "    # Any processing comes here\n",
    "    logger.info('body: ' + str(result.data))\n",
    "    data = json.loads(result.data)\n",
    "    logger.info('data: ' + str(data))\n",
    "\n",
    "    # Terminate the MEC application\n",
    "    mec_app_termination(sandbox_name, app_inst_id, sub_id)\n",
    "\n",
    "    logger.debug('Stopped at ' + time.strftime('%Y%m%d-%H%M%S'))\n",
    "    # End of function process_main\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    process_main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Subscribing to V2X message distribution server\n",
    "\n",
    "Here, we need to come back to the MEC 030 standard to create the type V2xMsgSubscription. It involves the creation of a set of basic types described below.\n",
    "\n",
    "These new type shall be 'JSON' serializable. It means that they have to implement the following methods:\n",
    "- to_dict()\n",
    "- to_str()\n",
    "- \\_\\_repr\\_\\_()\n",
    "- \\_\\_eq\\_\\_()\n",
    "- \\_\\_ne\\_\\_()\n",
    "**Reference:** ETSI GS MEC 030 V3.2.1 (2024-02) Clause 6.5.13 Type: LinkType\n"
Yann Garcia's avatar
Yann Garcia committed
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "class LinkType(object):\n",
    "    swagger_types = {'href': 'str'}\n",
    "    attribute_map = {'href': 'href'}\n",
    "    def __init__(self, href=None):  # noqa: E501\n",
    "        self._href = None\n",
    "        if href is not None:\n",
    "            self._href = href\n",
    "    @property\n",
    "    def href(self):\n",
    "        return self._href\n",
    "    @href.setter\n",
    "    def href(self, href):\n",
    "        self._href = href\n",
    "    def to_dict(self):\n",
    "        result = {}\n",
    "        for attr, _ in six.iteritems(self.swagger_types):\n",
    "            value = getattr(self, attr)\n",
    "            if isinstance(value, list):\n",
    "                result[attr] = list(map(\n",
    "                    lambda x: x.to_dict() if hasattr(x, 'to_dict') else x,\n",
    "            elif hasattr(value, 'to_dict'):\n",
    "                result[attr] = value.to_dict()\n",
    "            elif isinstance(value, dict):\n",
    "                result[attr] = dict(map(\n",
    "                    lambda item: (item[0], item[1].to_dict())\n",
    "                    if hasattr(item[1], 'to_dict') else item,\n",
    "                    value.items()\n",
    "                ))\n",
    "            else:\n",
    "                result[attr] = value\n",
    "        if issubclass(LinkType, dict):\n",
    "            for key, value in self.items():\n",
    "                result[key] = value\n",
    "        return result\n",
    "    def to_str(self):\n",
    "        return pprint.pformat(self.to_dict())\n",
    "    def __repr__(self):\n",
    "        return self.to_str()\n",
    "    def __eq__(self, other):\n",
    "        if not isinstance(other, LinkType):\n",
    "            return False\n",
    "        return self.__dict__ == other.__dict__\n",
    "    def __ne__(self, other):\n",
    "        return not self == other\n",
    "\n",
    "class Links(object):\n",
    "    swagger_types = {'self': 'LinkType'}\n",
    "    attribute_map = {'self': 'self'}\n",
    "    def __init__(self, self_=None):  # noqa: E501\n",
    "        self._self = None\n",
    "        if self_ is not None:\n",
    "            self._self = self_\n",
    "    @property\n",
    "    def self_(self):\n",
    "        return self._self\n",
    "    @self_.setter\n",
    "    def self_(self, self_):\n",
    "        self._self = self_\n",
    "    def to_dict(self):\n",
    "        result = {}\n",
    "        for attr, _ in six.iteritems(self.swagger_types):\n",
    "            value = getattr(self, attr)\n",
    "            if isinstance(value, list):\n",
    "                result[attr] = list(map(\n",
    "                    lambda x: x.to_dict() if hasattr(x, 'to_dict') else x,\n",
    "            elif hasattr(value, 'to_dict'):\n",
    "                result[attr] = value.to_dict()\n",
    "            elif isinstance(value, dict):\n",
    "                result[attr] = dict(map(\n",
    "                    lambda item: (item[0], item[1].to_dict())\n",
    "                    if hasattr(item[1], 'to_dict') else item,\n",
    "                    value.items()\n",
    "                ))\n",
    "            else:\n",
    "                result[attr] = value\n",
    "        if issubclass(Links, dict):\n",
    "            for key, value in self.items():\n",
    "                result[key] = value\n",
    "        return result\n",
    "    def to_str(self):\n",
    "        return pprint.pformat(self.to_dict())\n",
    "    def __repr__(self):\n",
    "        return self.to_str()\n",
    "    def __eq__(self, other):\n",
    "        if not isinstance(other, Links):\n",
    "            return False\n",
    "        return self.__dict__ == other.__dict__\n",
    "    def __ne__(self, other):\n",
    "        return not self == other\n",
    "\n",
    "class TimeStamp(object):\n",
    "    swagger_types = {'seconds': 'int', 'nano_seconds': 'int'}\n",
    "    attribute_map = {'seconds': 'seconds', 'nano_seconds': 'nanoSeconds'}\n",
    "    def __init__(self, seconds=None, nano_seconds=None):  # noqa: E501\n",
    "        self._seconds = None\n",
    "        self._nano_seconds = None\n",
    "        if seconds is not None:\n",
    "            self._seconds = seconds\n",
    "        if nano_seconds is not None:\n",
    "            self._nano_seconds = nano_seconds\n",
    "    @property\n",
    "    def seconds(self):\n",
    "        return self._seconds\n",
    "    @seconds.setter\n",
    "    def seconds(self, seconds):\n",
    "        self._seconds = seconds\n",
    "    @property\n",
    "    def nano_seconds(self):\n",
    "        return self._nano_seconds\n",
    "    @nano_seconds.setter\n",
    "    def nano_seconds(self, nano_seconds):\n",
    "        self._nano_seconds = nano_seconds\n",
    "    def to_dict(self):\n",
    "        result = {}\n",
    "        for attr, _ in six.iteritems(self.swagger_types):\n",
    "            value = getattr(self, attr)\n",
    "            if isinstance(value, list):\n",
    "                result[attr] = list(map(\n",
    "                    lambda x: x.to_dict() if hasattr(x, 'to_dict') else x,\n",
    "            elif hasattr(value, 'to_dict'):\n",
    "                result[attr] = value.to_dict()\n",
    "            elif isinstance(value, dict):\n",
    "                result[attr] = dict(map(\n",
    "                    lambda item: (item[0], item[1].to_dict())\n",
    "                    if hasattr(item[1], 'to_dict') else item,\n",
    "                    value.items()\n",
    "                ))\n",
    "            else:\n",
    "                result[attr] = value\n",
    "        if issubclass(TimeStamp, dict):\n",
    "            for key, value in self.items():\n",
    "                result[key] = value\n",
    "        return result\n",
    "    def to_str(self):\n",
    "        return pprint.pformat(self.to_dict())\n",
    "    def __repr__(self):\n",
    "        return self.to_str()\n",
    "    def __eq__(self, other):\n",
    "        if not isinstance(other, TimeStamp):\n",
    "            return False\n",
    "        return self.__dict__ == other.__dict__\n",
    "    def __ne__(self, other):\n",
    "        return not self == other"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
    "The cell below implements the V2xMsgSubscription data structure.\"}\n",
    "Reference: ETSI GS MEC 030 V3.2.1 (2024-02) Clause 6.3.5 Type: V2xMsgSubscription\n"
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "class V2xMsgSubscription(object):\n",
    "    swagger_types = {'links': 'Links', 'callback_reference': 'str', 'filter_criteria': 'V2xMsgSubscriptionFilterCriteria', 'request_test_notification': 'bool', 'subscription_type': 'str'}\n",
    "    attribute_map = {'links': 'Links', 'callback_reference': 'callbackReference', 'filter_criteria': 'filterCriteria', 'request_test_notification': 'requestTestNotification', 'subscription_type': 'subscriptionType'}\n",
    "    def __init__(self, links=None, callback_reference=None, filter_criteria=None, request_test_notification=None):  # noqa: E501\n",
    "        self._links = None\n",
    "        self._callback_reference = None\n",
    "        self._filter_criteria = None\n",
    "        self._request_test_notification = None\n",
    "        self._subscription_type = \"V2xMsgSubscription\"\n",
    "        if links is not None:\n",
    "            self.links = links\n",
    "        if callback_reference is not None:\n",
    "            self.callback_reference = callback_reference\n",
    "        if filter_criteria is not None:\n",
    "            self.filter_criteria = filter_criteria\n",
    "        if request_test_notification is not None:\n",
    "            self.request_test_notification = request_test_notification\n",
    "    @property\n",
    "    def links(self):\n",
    "        return self._links\n",
    "    @links.setter\n",
    "    def links(self, links):\n",
    "        self_.links = links\n",
    "    @property\n",
    "    def callback_reference(self):\n",
    "        return self._callback_reference\n",
    "    @callback_reference.setter\n",
    "    def callback_reference(self, callback_reference):\n",
    "        self._callback_reference = callback_reference\n",
    "    @property\n",
    "    def links(self):\n",
    "        return self._links\n",
    "    @links.setter\n",
    "    def links(self, links):\n",
    "        self._links = links\n",
    "    @property\n",
    "    def filter_criteria(self):\n",
    "        return self._filter_criteria\n",
    "    @filter_criteria.setter\n",
    "    def filter_criteria(self, filter_criteria):\n",
    "        self._filter_criteria = filter_criteria\n",
    "    @property\n",
    "    def request_test_notification(self):\n",
    "        return self._request_test_notification\n",
    "    @request_test_notification.setter\n",
    "    def request_test_notification(self, request_test_notification):\n",
    "        self._request_test_notification = request_test_notification\n",
    "    @property\n",
    "    def subscription_type(self):\n",
    "        return self._subscription_type\n",
    "    def to_dict(self):\n",
    "        result = {}\n",
    "        for attr, _ in six.iteritems(self.swagger_types):\n",
    "            value = getattr(self, attr)\n",
    "            if isinstance(value, list):\n",
    "                result[attr] = list(map(\n",
    "                    lambda x: x.to_dict() if hasattr(x, 'to_dict') else x,\n",
    "            elif hasattr(value, 'to_dict'):\n",
    "                result[attr] = value.to_dict()\n",
    "            elif isinstance(value, dict):\n",
    "                result[attr] = dict(map(\n",
    "                    lambda item: (item[0], item[1].to_dict())\n",
    "                    if hasattr(item[1], 'to_dict') else item,\n",
    "                    value.items()\n",
    "                ))\n",
    "            else:\n",
    "                result[attr] = value\n",
    "        if issubclass(V2xMsgSubscription, dict):\n",
    "            for key, value in self.items():\n",
    "                result[key] = value\n",
    "        return result\n",
    "    def to_str(self):\n",
    "        return pprint.pformat(self.to_dict())\n",
    "    def __repr__(self):\n",
    "        return self.to_str()\n",
    "    def __eq__(self, other):\n",
    "        if not isinstance(other, V2xMsgSubscription):\n",
    "            return False\n",
    "        return self.__dict__ == other.__dict__\n",
    "    def __ne__(self, other):\n",
    "        return not self == other\n",
    "\n",
    "class V2xMsgSubscriptionFilterCriteria(object):\n",
    "    swagger_types = {'msg_type': 'list[str]', 'std_organization': 'str'}\n",
    "    attribute_map = {'msg_type': 'MsgType', 'std_organization': 'stdOrganization'}\n",
    "    def __init__(self, msg_type, std_organization):  # noqa: E501\n",
    "        self._msg_type = None\n",
    "        self._std_organization = None\n",
    "        self.msg_type = msg_type\n",
    "        self.std_organization = std_organization\n",
    "    @property\n",
    "    def msg_type(self):\n",
    "        return self._msg_type\n",
    "    @msg_type.setter\n",
    "    def msg_type(self, msg_type):\n",
    "        self._msg_type = msg_type\n",
    "    @property\n",
    "    def std_organization(self):\n",
    "        return self._std_organization\n",
    "    @std_organization.setter\n",
    "    def std_organization(self, std_organization):\n",
    "        self._std_organization = std_organization\n",
    "    def to_dict(self):\n",
    "        result = {}\n",
    "        for attr, _ in six.iteritems(self.swagger_types):\n",
    "            value = getattr(self, attr)\n",
    "            if isinstance(value, list):\n",
    "                result[attr] = list(map(\n",
    "                    lambda x: x.to_dict() if hasattr(x, 'to_dict') else x,\n",
    "            elif hasattr(value, 'to_dict'):\n",
    "                result[attr] = value.to_dict()\n",
    "            elif isinstance(value, dict):\n",
    "                result[attr] = dict(map(\n",
    "                    lambda item: (item[0], item[1].to_dict())\n",
    "                    if hasattr(item[1], 'to_dict') else item,\n",
    "                    value.items()\n",
    "                ))\n",
    "            else:\n",
    "                result[attr] = value\n",
    "        if issubclass(V2xMsgSubscriptionFilterCriteria, dict):\n",
    "            for key, value in self.items():\n",
    "                result[key] = value\n",
    "        return result\n",
    "    def to_str(self):\n",
    "        return pprint.pformat(self.to_dict())\n",
    "    def __repr__(self):\n",
    "        return self.to_str()\n",
    "    def __eq__(self, other):\n",
    "        if not isinstance(other, V2xMsgSubscriptionFilterCriteria):\n",
    "            return False\n",
    "        return self.__dict__ == other.__dict__\n",
    "    def __ne__(self, other):\n",
    "        return not self == other"
   ]
  },
Yann Garcia's avatar
Yann Garcia committed
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is the V2X message subscription function. The HTTP Request message body contains a 'JSON' serialized instance of the class V2xMsgSubscription.\n",
    "\n",
    "Reference: ETSI GS MEC 030 V3.2.1 (2024-02) Clause 5.5.10 V2X message interoperability\n"
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
Yann Garcia's avatar
Yann Garcia committed
    "def subscribe_v2x_message(sandbox_name: str, v2xMsgSubscription: V2xMsgSubscription) -> object:\n",
    "    \"\"\"\n",
    "    Request to subscribe the V2X messages which come from different vehicle OEMs or operators\n",
    "    :param sandbox_name: The MEC Sandbox instance to use\n",
    "    :param app_inst_id: The MEC application instance identifier\n",
    "    :param sub_id: The subscription identifier\n",
    "    :return The HTTP response, the HTTP response status, the subscription identifier and the subscription URL on success, None otherwise\n",
    "    :see ETSI GS MEC 030 V3.2.1 (2024-02) Clause 5.5.10 V2X message interoperability\n",
    "    \"\"\"\n",
    "    global MEC_PLTF, logger, service_api\n",
    "    logger.debug('>>> subscribe_v2x_message: v2xMsgSubscription: ' + str(v2xMsgSubscription))\n",
    "        url = '/{sandbox_name}/{mec_pltf}/vis/v2/subscriptions'\n",
    "        logger.debug('subscribe_v2x_message: url: ' + url)\n",
    "        path_params = {}\n",
    "        path_params['sandbox_name'] = sandbox_name\n",
    "        path_params['mec_pltf'] = MEC_PLTF\n",
    "        header_params = {}\n",
    "        # HTTP header `Accept`\n",
    "        header_params['Accept'] = 'application/json'  # noqa: E501\n",
    "        # HTTP header `Content-Type`\n",
    "        header_params['Content-Type'] = 'application/json'  # noqa: E501\n",
    "        (result, status, headers) = service_api.call_api(url, 'POST', header_params=header_params, path_params=path_params, body=v2xMsgSubscription, async_req=False)\n",
Yann Garcia's avatar
Yann Garcia committed
    "        return (result, status, extract_sub_id(headers['Location']), headers['Location'])\n",
    "    except ApiException as e:\n",
    "        logger.error('Exception when calling call_api: %s\\n' % e)\n",
    "    # End of function subscribe_v2x_message"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is a generic function to delete any MEC service subscription based on the subscription resource URL provided in the Location header of the subscription creation response."
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "def delete_mec_subscription(resource_url: str) -> int:\n",
    "    \"\"\"\n",
    "    Delete any existing MEC subscription\n",
    "    :param resource_url: The subscription URL\n",
    "    :return 0 on success, -1 otherwise\n",
    "    \"\"\"\n",
    "    global MEC_PLTF, logger, service_api\n",
    "\n",
    "    logger.debug('>>> delete_mec_subscription: resource_url: ' + resource_url)\n",
    "    try:\n",
    "        res = urllib3.util.parse_url(resource_url)\n",
    "        if res is None:\n",
    "            logger.error('delete_mec_subscription: Failed to paerse URL')\n",
    "            return -1\n",
    "        header_params = {}\n",
    "        # HTTP header `Accept`\n",
    "        header_params['Accept'] = 'application/json'  # noqa: E501\n",
    "        # HTTP header `Content-Type`\n",
    "        header_params['Content-Type'] = 'application/json'  # noqa: E501\n",
    "        service_api.call_api(res.path, 'DELETE', header_params=header_params, async_req=False)\n",
    "        return 0\n",
    "    except ApiException as e:\n",
    "        logger.error('Exception when calling call_api: %s\\n' % e)\n",
    "    return -1\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finaly, here is how to implement the V2X message subscription:"
   ]
  },
  {
   "cell_type": "code",
Yann Garcia's avatar
Yann Garcia committed
   "execution_count": null,
Yann Garcia's avatar
Yann Garcia committed
   "outputs": [],
   "source": [
    "def process_main():\n",
    "    \"\"\"\n",
    "    This is the second sprint of our skeleton of our MEC application:\n",
    "        - Mec application setup\n",
    "        - Subscribe to V2XMessage\n",
    "        - Delete subscription\n",
    "        - Mec application termination\n",
    "    \"\"\" \n",
    "    global MEC_PLTF, CALLBACK_URI, logger\n",
    "\n",
    "    logger.debug('Starting at ' + time.strftime('%Y%m%d-%H%M%S'))\n",
    "    logger.debug('\\t pwd= ' + os.getcwd())\n",