Как мне найти маршрут карты с помощью Azure IoT?

#c# #azure #maps #iot #azure-iot-hub

Вопрос:

Я пытаюсь завершить первое руководство по пути обучения Azure IoT, но каждый раз, когда я пытаюсь заставить устройство найти клиента, оно сообщает «Не удалось найти маршрут карты». в консоли. Я выполнил все шаги, просмотрел код, и нет ответов на устранение неполадок для этой конкретной ошибки. Устройство подключено к моей программе, оно просто не может найти маршрут карты.

 static void GetRoute(StateEnum newState)
    {
        // Set the state to ready, until the new route arrives.
        state = StateEnum.ready;

        var req = new RouteRequestDirections
        {
            Query = FormattableString.Invariant($"{currentLat},{currentLon}:{destinationLat},{destinationLon}")
        };
        var directions = azureMapsServices.GetRouteDirections(req).Resu<

        if (directions.Error != null || directions.Result == null)
        {
            // Handle any error.
            redMessage("Failed to find map route");
        }
        else
        {
            int nPoints = directions.Result.Routes[0].Legs[0].Points.Length;
            greenMessage($"Route found. Number of points = {nPoints}");

            // Clear the path. Add two points for the start point and destination.
            path = new double[nPoints   2, 2];
            int c = 0;

            // Start with the current location.
            path[c, 0] = currentLat;
            path[c, 1] = currentLon;
              c;

            // Retrieve the route and push the points onto the array.
            for (var n = 0; n < nPoints; n  )
            {
                var x = directions.Result.Routes[0].Legs[0].Points[n].Latitude;
                var y = directions.Result.Routes[0].Legs[0].Points[n].Longitude;
                path[c, 0] = x;
                path[c, 1] = y;
                  c;
            }

            // Finish with the destination.
            path[c, 0] = destinationLat;
            path[c, 1] = destinationLon;

            // Store the path length and time taken, to calculate the average speed.
            var meters = directions.Result.Routes[0].Summary.LengthInMeters;
            var seconds = directions.Result.Routes[0].Summary.TravelTimeInSeconds;
            var pathSpeed = meters / seconds;

            double distanceApartInMeters;
            double timeForOneSection;

            // Clear the time on the path array. The path array is 1 less than the points array.
            timeOnPath = new double[nPoints   1];

            // Calculate how much time is required for each section of the path.
            for (var t = 0; t < nPoints   1; t  )
            {
                // Calculate distance between the two path points, in meters.
                distanceApartInMeters = DistanceInMeters(path[t, 0], path[t, 1], path[t   1, 0], path[t   1, 1]);

                // Calculate the time for each section of the path.
                timeForOneSection = distanceApartInMeters / pathSpeed;
                timeOnPath[t] = timeForOneSection;
            }
            truckOnSection = 0;
            truckSectionsCompletedTime = 0;
            timeOnCurrentTask = 0;

            // Update the state now the route has arrived. Either: enroute or returning.
            state = newState;
        }
    }
 

Комментарии:

1. В коде, как мы видим, вы инициализировали переменные направления как azureMapsServices.GetRouteDirections(req).Result и в условии if, которое вы проверяете directions.Result == null . Вместо этого не могли бы вы попробовать поместить directions == null или удалить .Result при инициализации переменной directions . Проверьте, поможет ли это, тогда я опубликую его в качестве ответа.

Ответ №1:

Для ошибки убедитесь, что:

Ключевым вызовом в приведенном выше коде является var directions = azureMapsServices.GetRouteDirections(req).Resu< . directions Структура сложная. Рассмотрите возможность установки точки останова в этом методе и изучения содержимого directions .

Вы можете использовать приведенный ниже пример кода, чтобы добавить прямой метод доставки клиенту :

 static Task<MethodResponse> CmdGoToCustomer(MethodRequest methodRequest, object userContext)
     {
         try
         {
             // Pick up variables from the request payload, with the name specified in IoT Central.
             var payloadString = Encoding.UTF8.GetString(methodRequest.Data);
             int customerNumber = Int32.Parse(payloadString);

             // Check for a valid key and customer ID.
             if (customerNumber >= 0 amp;amp; customerNumber < customer.Length)
             {
                 switch (state)
                 {
                     case StateEnum.dumping:
                     case StateEnum.loading:
                     case StateEnum.delivering:
                         eventText = "Unable to act - "   state;
                         break;

                     case StateEnum.ready:
                     case StateEnum.enroute:
                     case StateEnum.returning:
                         if (contents == ContentsEnum.empty)
                         {
                             eventText = "Unable to act - empty";
                         }
                         else
                         {
                             // Set event only when all is good.
                             eventText = "New customer: "   customerNumber.ToString();

                             destinationLat = customer[customerNumber, 0];
                             destinationLon = customer[customerNumber, 1];

                             // Find route from current position to destination, storing route.
                             GetRoute(StateEnum.enroute);
                         }
                         break;
                 }

                 // Acknowledge the direct method call with a 200 success message.
                 string result = "{"result":"Executed direct method: "   methodRequest.Name   ""}";
                 return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
             }
             else
             {
                 eventText = $"Invalid customer: {customerNumber}";

                 // Acknowledge the direct method call with a 400 error message.
                 string result = "{"result":"Invalid customer"}";
                 return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 400));
             }
         }
         catch
         {
             // Acknowledge the direct method call with a 400 error message.
             string result = "{"result":"Invalid call"}";
             return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 400));
         }
     }
 

Для получения дополнительной информации, пожалуйста, обратитесь к этому РУКОВОДСТВУ MS: Создайте свое первое приложение Azure IoT Central и создайте программный проект для реального устройства

MS Q amp; A: Ошибка — создайте свое первое приложение Azure IoT Central