### OCM Client Library Quick Start Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/README.md Demonstrates how to install the OCM API client library, create an instance, and query reference data and nearby charging locations using C#. ```csharp // 1. Install the client library // dotnet add package OCM.API.Client // 2. Create a client using var client = new OCMClient( baseUrl: "https://api.openchargemap.org/v3", apiKey: "YOUR_API_KEY" // Optional ); // 3. Query reference data var refData = await client.GetCoreReferenceDataAsync(); // 4. Search for nearby locations var filters = new SearchFilters { Latitude = 51.5074, // London Longitude = -0.1278, Distance = 5, DistanceUnit = DistanceUnit.Miles, MaxResults = 50, IncludeUserComments = true }; var pois = await client.GetPOIListAsync(filters); foreach (var poi in pois ?? Enumerable.Empty()) { Console.WriteLine($"OCM-{poi.ID}: {poi.AddressInfo.Title}"); foreach (var conn in poi.Connections ?? new List()) { Console.WriteLine($" {conn.ConnectionType.Title}: {conn.PowerKW}kW"); } } ``` -------------------------------- ### Install Dependencies Source: https://github.com/openchargemap/ocm-system/blob/master/Localisation/readme.md On a new development machine, run 'npm install' to fetch project dependencies, including Grunt and other build tools. ```bash npm install ``` -------------------------------- ### Install Docker on Ubuntu 18.04 Source: https://github.com/openchargemap/ocm-system/blob/master/API/OCM.Net/OCM.API.Worker/README.md Installs Docker and its prerequisites on an Ubuntu 18.04 system. ```bash sudo apt update sudo apt install apt-transport-https ca-certificates curl software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable" ``` -------------------------------- ### OCPI Provider Configuration Example Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Common/Providers/OCPI/readme.md Example JSON structure for configuring an OCPI provider. Use this in the 'ocpi-providers.json' file to define provider details, endpoint URLs, and operator mappings. ```json { "Providers": [ { "ProviderName": "my-new-provider", "OutputNamePrefix": "mynewprovider", "Description": "My New OCPI Provider", "DataProviderId": 99, "LocationsEndpointUrl": "https://api.example.com/ocpi/2.2/locations", "AuthHeaderKey": "Authorization", "CredentialKey": "OCPI-MYPROVIDER", "DefaultOperatorId": 1234, "IsAutoRefreshed": true, "IsProductionReady": true, "IsEnabled": true, "AllowDuplicatePOIWithDifferentOperator": true, "OperatorMappings": { "Operator Name From OCPI": 1234, "Another Operator": 5678 }, "ExcludedLocationIds": [] } ] } ``` -------------------------------- ### Import Status JSON Example Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Example JSON output from the import status file, showing details of the last completed import. ```json { "LastImportedProvider": "zepto.pl", "DateLastImport": "2025-01-15T10:05:23.456Z", "LastImportStatus": "Completed Successfully", "ProcessingTimeSeconds": 322.5 } ``` -------------------------------- ### C# Permission Checking Examples Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/architecture.md Provides examples of C# methods used to check user permissions within the system. ```csharp UserManager.IsUserAdministrator(user) UserManager.HasUserPermission(user, countryId, PermissionLevel.Editor) POIManager.CanUserEditPOI(poi, user) ``` -------------------------------- ### Create AddressInfo Object Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/core-models.md Example of creating an AddressInfo object with essential details for a charging location. ```csharp var address = new AddressInfo { Title = "Main Charging Hub", AddressLine1 = "123 Green Street", Town = "London", StateOrProvince = "England", Postcode = "SW1A 1AA", Country = new Country { ID = 1, Title = "United Kingdom" }, Latitude = 51.5074, Longitude = -0.1278, ContactEmail = "info@example.com" }; ``` -------------------------------- ### Worker Shutdown Log Example Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Example log output showing the import worker stopping and listing currently tracked failed imports. ```log [2025-01-15 18:00:00] Import Worker is stopping [2025-01-15 18:00:00] Current failed imports being tracked: afdc.energy.gov, sitronics ``` -------------------------------- ### Run OCM API Server (Release) Source: https://github.com/openchargemap/ocm-system/blob/master/API/OCM.Net/OCM.API.Worker/README.md Starts the OCM API server in release mode, listening on all network interfaces on port 5000. ```bash dotnet run -c Release --urls http://0.0.0.0:5000 ``` -------------------------------- ### Enable OCM API Service on Boot Source: https://github.com/openchargemap/ocm-system/blob/master/API/OCM.Net/OCM.API.Worker/README.md Configures the OCM API service to start automatically when the host restarts. ```bash sudo systemctl enable ocm-api.service ``` -------------------------------- ### Example: Retrieve and Display POI Details Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/managers.md Demonstrates how to fetch a POI with extended information and mirror database caching, then access and print its operator, status, and connection details. ```csharp var manager = new POIManager(); var poi = await manager.Get(12345, includeExtendedInfo: true, allowMirrorDB: true); if (poi != null) { Console.WriteLine($"Operator: {poi.OperatorInfo.Title}"); Console.WriteLine($"Status: {poi.StatusType.Title}"); foreach (var conn in poi.Connections) { Console.WriteLine($" {conn.ConnectionType.Title}: {conn.PowerKW}kW"); } } ``` -------------------------------- ### Create ConnectionInfo Object Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/core-models.md Example of creating a ConnectionInfo object, specifying connector type, power, and quantity. Power can be set directly or computed. ```csharp var connection = new ConnectionInfo { ConnectionTypeID = 33, // CCS Combo Type 2 Amps = 200, Voltage = 400, CurrentTypeID = (int)StandardCurrentTypes.ThreePhaseAC, Quantity = 2, PowerKW = 150 // or computed as ~120kW from Amps/Voltage }; ``` -------------------------------- ### Cache Status JSON Example Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/architecture.md Shows the structure of the system status response, used for cache change detection. ```json { "poiDataLastModified": "2024-01-20T14:30:00Z", "maxPoiId": 45678, "dataHash": "a1b2c3d4e5f6..." } ``` -------------------------------- ### OCMClient Library Example Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/configuration.md Demonstrates how to use the OCMClient library to perform a search with specified filters and process the results. Requires an API key and base URL. ```csharp using var client = new OCMClient("https://api.openchargemap.org/v3", apiKey); var filters = new SearchFilters { Latitude = 51.5074, Longitude = -0.1278, Distance = 5, DistanceUnit = DistanceUnit.Miles, MaxResults = 50, IncludeUserComments = true, Verbose = true }; var pois = await client.GetPOIListAsync(filters); foreach (var poi in pois) { Console.WriteLine($"{poi.ID}: {poi.AddressInfo.Title}"); } ``` -------------------------------- ### Get All Reference Data Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Retrieves all available reference data, such as countries, connection types, and operator information. ```bash curl "https://api.openchargemap.org/v4/referencedata" ``` -------------------------------- ### Provider Import Due Log Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Example log output showing a provider is due for import and will be retried after its failure threshold expires. ```log [2025-01-16 10:02:16] Checking for imports due.. [2025-01-16 10:02:16] Provider 'afdc.energy.gov' removed from failed imports tracking - threshold expired, will be retried if due [2025-01-16 10:02:17] Performing import for 'afdc.energy.gov' (ID: 23, Last imported: 48.2 hours ago) ``` -------------------------------- ### Example: Configure and Execute POI List Query Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/managers.md Demonstrates setting up APIRequestParams to filter charging locations by location, distance, power, data type, and other criteria, then executing the query using GetPOIListAsync. ```csharp var filter = new APIRequestParams { Latitude = 51.5074, Longitude = -0.1278, Distance = 10, DistanceUnit = Common.Model.DistanceUnit.KM, MaxResults = 100, AllowMirrorDB = true, AllowDataStoreDB = false, // Use MongoDB cache only MinPowerKW = 50, // Fast chargers only IsOpenData = true, // Open data only IncludeComments = true, IsVerboseOutput = true }; var pois = await manager.GetPOIListAsync(filter); ``` -------------------------------- ### Standard JSON Response Formatting Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Example of requesting a standard JSON response from the API, with options for output format and verbosity. ```bash curl "https://api.openchargemap.org/v4/poi?output=json&verbose=true" ``` -------------------------------- ### Run OCM API Server (Debug) Source: https://github.com/openchargemap/ocm-system/blob/master/API/OCM.Net/OCM.API.Worker/README.md Starts the OCM API server in debug mode, listening on all network interfaces on port 5000. ```bash dotnet run --urls http://0.0.0.0:5000 ``` -------------------------------- ### Authenticated API Request Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Example of how to include an API key for authenticated requests to the Open Charge Map API. ```bash # With authentication curl -H "X-API-Key: YOUR_API_KEY" "https://api.openchargemap.org/v4/poi?latitude=51.5074&longitude=-0.1278" ``` -------------------------------- ### No Imports Due Log Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Example log output indicating that no providers are currently due for import and when the next one is scheduled. ```log [2025-01-15 10:05:00] Checking for imports due.. [2025-01-15 10:05:01] No imports currently due. Next provider 'powergo' due in 6.2 hours at 2025-01-15 16:15:00 UTC ``` -------------------------------- ### Start OCM Import Worker Container with an Entrypoint Shell Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Starts the OCM Import Worker container and overrides the default entrypoint to `/bin/bash`, allowing interactive shell access for debugging. The container is removed upon exit. ```bash # Start container with shell docker run -it --rm \ --entrypoint /bin/bash \ ocm-import-worker:latest ``` -------------------------------- ### Example POI Response Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md A sample JSON response for a Point of Interest (POI) query, detailing charging station information. ```json [ { "id": 12345, "uuid": "550e8400-e29b-41d4-a716-446655440000", "dataProviderId": 1, "operatorId": 5, "usageTypeId": 1, "statusTypeId": 50, "submissionStatusTypeId": 200, "dataQualityLevel": 4, "dateCreated": "2023-06-15T10:30:00Z", "dateLastStatusUpdate": "2024-01-20T14:00:00Z", "dateLastConfirmed": "2024-01-15T08:00:00Z", "numberofPoints": 4, "usageCost": "Free", "generalComments": "Located near parking area", "addressInfo": { "id": 67890, "title": "Downtown Charging Hub", "addressLine1": "123 Green Street", "addressLine2": null, "town": "London", "stateOrProvince": "England", "postcode": "SW1A 1AA", "countryId": 1, "country": { "id": 1, "title": "United Kingdom", "isoCode": "GB" }, "latitude": 51.5074, "longitude": -0.1278, "contactTelephone1": "+44 20 7946 0958", "contactEmail": "info@example.com", "accessComments": "Open 24/7", "relatedUrl": "https://example.com" }, "connections": [ { "id": 1, "connectionTypeId": 33, "connectionType": { "id": 33, "title": "CCS Combo Type 2", "formalName": "IEC 62196-3 Type 2" }, "statusTypeId": 50, "statusType": { "id": 50, "title": "Operational" }, "levelId": 3, "level": { "id": 3, "title": "DC Fast" }, "amps": 200, "voltage": 400, "powerKw": 150, "currentTypeId": 20, "currentType": { "id": 20, "title": "Three Phase AC" }, "quantity": 2, "comments": "Supports vehicle-to-grid" } ], "dataProvider": { "id": 1, "title": "Open Charge Map Contributors", "websiteUrl": "https://openchargemap.org", "isOpenDataLicensed": true }, "operatorInfo": { "id": 5, "title": "ChargePoint", "websiteUrl": "https://www.chargepoint.com" }, "usageType": { "id": 1, "title": "Public" }, "statusType": { "id": 50, "title": "Operational" }, "submissionStatus": { "id": 200, "title": "Submitted, Published" }, "userComments": [ { "id": 1001, "userId": 42, "comment": "Charger works great, very fast", "commentTypeId": 10, "dateCreated": "2024-01-10T15:30:00Z", "rating": 5 } ], "mediaItems": [ { "id": 5001, "itemUrl": "https://media.example.com/poi_12345_001.jpg", "itemThumbnailUrl": "https://media.example.com/poi_12345_001_thumb.jpg", "comment": "Location sign", "dateCreated": "2023-11-01T09:00:00Z" } ] } ] ``` -------------------------------- ### REST API Query for Reference Data Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/README.md Example using curl to retrieve core reference data from the OCM API. ```bash # Get reference data curl "https://api.openchargemap.org/v4/referencedata" ``` -------------------------------- ### Provider Selection Logic Example Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Illustrates the dynamic priority logic for selecting the next provider to import. It prioritizes providers with the oldest 'DateLastImported' greater than 24 hours ago, while excluding those recently failed. ```csharp // Selects provider with oldest DateLastImported > 24h // AND not recently failed // provider[2] (48h old, never failed) ? // provider[5] (30h old, never failed) ? // provider[1] (25h old, never failed) // ? Skips provider[3] (50h old, failed 2h ago) ``` -------------------------------- ### Deploy OCM API Worker as Systemd Service Source: https://github.com/openchargemap/ocm-system/blob/master/API/OCM.Net/OCM.API.Worker/README.md Copies the service file, creates a symlink, reloads systemd, and starts the OCM API service. ```bash sudo cp ocm-api.service /etc/systemd/system/ocm-api.service sudo ln -s -f /opt/ocm-api/OCM.API.Worker /usr/sbin/ocm-api sudo systemctl daemon-reload sudo systemctl start ocm-api ``` -------------------------------- ### camelCase Property Names Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Example of requesting API responses with camelCase property names instead of the default PascalCase. ```bash curl "https://api.openchargemap.org/v4/poi?camelcase=true" ``` -------------------------------- ### Example DataProvider API Response Structure Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Illustrates the expected JSON structure for the DataProviders list returned by the OCM API, including essential fields like ID, Title, DateLastImported, and IsApprovedImport. ```json { "DataProviders": [ { "ID": 44, "Title": "zepto.pl", "DateLastImported": "2025-01-14T08:30:00Z", "IsApprovedImport": true } ] } ``` -------------------------------- ### Code-Based OCPI Provider Implementation in C# Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Common/Providers/OCPI/readme.md Example C# class for a custom OCPI import provider. Inherits from ImportProvider_OCPI and implements necessary configurations like provider name, endpoint, and operator mappings. ```csharp using System.Collections.Generic; namespace OCM.Import.Providers.OCPI { public class ImportProvider_MyProvider : ImportProvider_OCPI, IImportProvider { public ImportProvider_MyProvider() : base() { ProviderName = "myprovider"; OutputNamePrefix = "myprovider"; IsAutoRefreshed = true; IsProductionReady = true; CredentialKey = "OCPI-MYPROVIDER"; // or null if no auth needed DefaultOperatorID = 1234; Init(dataProviderId: 99, "https://api.example.com/ocpi/2.2/locations"); } public override Dictionary GetOperatorMappings() { return new Dictionary() { { "My Operator", 1234 } }; } } } ``` -------------------------------- ### Build OCM Import Worker Image with Docker Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Builds the Docker image for the OCM Import Worker from the repository root. Ensure Docker is installed and accessible. ```bash # Build using Docker docker build -f Import/OCM.Import.Worker/Dockerfile -t ocm-import-worker:latest . # Or build using Docker Compose cd Import/OCM.Import.Worker docker-compose build ``` -------------------------------- ### Get System Sync Data Since Specific Date Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Retrieves POI and reference data changes made since a specific ISO 8601 formatted date. This allows for targeted data synchronization. ```bash curl "https://api.openchargemap.org/v4/system/sync?dateModified=2024-01-01T00:00:00Z" ``` -------------------------------- ### EF Core DbContext Configuration with Logging and Lazy Loading Source: https://github.com/openchargemap/ocm-system/blob/master/API/OCM.Net/OCM.API.Core/DataModelRefresh.txt Configure the DbContext to use a console logger and enable lazy loading. This example demonstrates setting up connection strings for both debug and live environments. ```csharp public static readonly ILoggerFactory ConsoleLogger = LoggerFactory.Create(builder => { builder.AddConsole(); }); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseLoggerFactory(ConsoleLogger); optionsBuilder.UseLazyLoadingProxies(); ar conn = "OCMEntities"; #if DEBUG conn = "OCMEntitiesDebug"; #endif optionsBuilder.UseSqlServer(System.Configuration.ConfigurationManager.ConnectionStrings[conn].ConnectionString, x => { x.UseNetTopologySuite(); x.CommandTimeout((int)TimeSpan.FromMinutes(5).TotalSeconds); x.EnableRetryOnFailure(3); }); #if DEBUG optionsBuilder.EnableDetailedErrors(true); optionsBuilder.EnableSensitiveDataLogging(true); #endif } } ``` -------------------------------- ### Manage Services with Docker Compose Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Commands for managing the OCM Import Worker and its related services using Docker Compose. This includes starting, stopping, and viewing logs. ```bash # Start services docker-compose up -d # View logs docker-compose logs -f # Stop services docker-compose down # Rebuild and restart docker-compose up -d --build # Remove volumes docker-compose down -v ``` -------------------------------- ### Get All System Sync Data Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Retrieves all POI and reference data changes made in the last month. This is useful for synchronizing local data with the Open Charge Map system. ```bash curl "https://api.openchargemap.org/v4/system/sync" ``` -------------------------------- ### OCM Client Library Usage Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/architecture.md Demonstrates how to instantiate the OCMClient and fetch core reference data and points of interest using search filters. Ensure you have the base URL and API key ready. ```csharp using var client = new OCMClient(baseUrl, apiKey); var refData = await client.GetCoreReferenceDataAsync(); var pois = await client.GetPOIListAsync(filters); ``` -------------------------------- ### Stop, Start, Restart, and Remove OCM Import Worker Container Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Provides basic management commands for the OCM Import Worker container: stopping, starting, restarting, and forcefully removing it. ```bash # Stop container docker stop ocm-import-worker # Start container docker start ocm-import-worker # Restart container docker restart ocm-import-worker # Remove container docker rm -f ocm-import-worker ``` -------------------------------- ### Initialize OCMClient Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/ocmclient.md Instantiate the OCMClient with the base API URL, an API key, and an optional logger and user agent. ```csharp public OCMClient(string baseUrl, string apiKey, ILogger logger = null, string userAgent = "OCM-API-Client") ``` -------------------------------- ### Get Full POI Details Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/managers.md A convenience method to retrieve a complete POI object, including all associated reference data. This is equivalent to calling the Get method with specific parameters for extended information and mirror database usage. ```csharp public async Task GetFullDetails(int id) ``` -------------------------------- ### Use Custom Docker Compose Files Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Demonstrates how to use specific or multiple Docker Compose files to manage services. This allows for different configurations, such as production or development overrides. ```bash # Use a specific compose file docker-compose -f docker-compose.prod.yml up -d # Use multiple compose files (merge configurations) docker-compose -f docker-compose.yml -f docker-compose.override.yml up -d ``` -------------------------------- ### Server-Side POI Management Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/README.md Demonstrates server-side integration using manager classes for fetching single POIs with full details and querying POIs with advanced filters. Includes settings for caching and data sources. ```csharp // Using manager classes directly (server-side only) var manager = new POIManager { LoadUserComments = true }; // Get single POI with all details var poi = await manager.GetFullDetails(12345); // Query with advanced filters var filter = new APIRequestParams { Latitude = 51.5074, Longitude = -0.1278, Distance = 10, DistanceUnit = DistanceUnit.KM, MinPowerKW = 50, IsOpenData = true, IncludeComments = true, MaxResults = 200, AllowMirrorDB = true, // Use MongoDB cache AllowDataStoreDB = false }; var results = await manager.GetPOIListAsync(filter); ``` -------------------------------- ### Standard Entity Types Enumeration Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/types.md Defines the types of entities managed within the system, with POI (Point of Interest) being a primary example. ```csharp public enum StandardEntityTypes { POI = 1 } ``` -------------------------------- ### API Key Authentication Headers Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/architecture.md Demonstrates how to include an API key for authentication in requests. ```text Header: X-API-Key: Query: ?apikey= ``` -------------------------------- ### Dispose OCMClient with Using Statement Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/ocmclient.md Demonstrates the recommended way to dispose of the OCMClient instance using a 'using' statement for automatic resource management. ```csharp using (var client = new OCMClient(baseUrl, apiKey)) { var results = await client.GetPOIListAsync(filters); } // Disposed automatically ``` -------------------------------- ### Configure Azure Key Vault for Production Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Sets environment variables for integrating with Azure Key Vault for secure credential management in production environments. Replace placeholders with your actual Azure details. ```bash -e KeyVaultName=your-keyvault-name -e AZURE_CLIENT_ID=your-client-id -e AZURE_CLIENT_SECRET=your-client-secret -e AZURE_TENANT_ID=your-tenant-id ``` -------------------------------- ### Get System Status Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Retrieves the current system health and cache status information, including API version and data modification timestamps. ```json { "systemVersion": "3", "poiDataLastModified": "2024-01-20T14:30:00Z", "poiDataLastCreated": "2024-01-15T08:00:00Z", "maxPoiId": 45678, "dataHash": "a1b2c3d4e5f6g7h8i9j0" } ``` -------------------------------- ### Get Operators Filtered by Country Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Retrieves operator information, filtered to include only operators present in a specified country. Requires the country ID. ```bash curl "https://api.openchargemap.org/v4/referencedata?filteroperatorsoncountry=true&countryid=1" ``` -------------------------------- ### Build OCM Import Worker for Multiple Architectures Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Builds the Docker image for multiple platforms (e.g., amd64 and arm64) using Docker Buildx. The `--push` flag uploads the multi-arch image to a registry. ```bash # Create builder docker buildx create --name ocm-builder --use # Build for multiple platforms docker buildx build \ --platform linux/amd64,linux/arm64 \ -f Import/OCM.Import.Worker/Dockerfile \ -t ocm-import-worker:latest \ --push \ . ``` -------------------------------- ### Get Complete Reference Data (Asynchronous) Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/managers.md Asynchronously retrieves the complete set of reference data. Returns a Task that will complete with the CoreReferenceData object. ```csharp public async Task GetCoreReferenceDataAsync() ``` -------------------------------- ### API Key Authentication with cURL Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Demonstrates how to authenticate API requests using an API key, either as a query parameter or a request header. The header method is preferred. ```bash # Query parameter curl "https://api.openchargemap.org/v4/poi?apikey=YOUR_API_KEY" # Request header (preferred) curl -H "X-API-Key: YOUR_API_KEY" "https://api.openchargemap.org/v4/poi" ``` -------------------------------- ### Temporarily Disable Provider Import Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Example JSON configuration snippet showing how to temporarily disable imports for a specific provider by commenting it out in the EnabledImports list. ```json "EnabledImports": [ // "afdc.energy.gov", // Temporarily disabled - investigate API changes "powergo", "zepto.pl" ] ``` -------------------------------- ### User Session Authentication with C# Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Shows how to authenticate advanced operations like submissions and edits using user credentials (username and session token) with the OCMClient in C#. ```csharp var credentials = new APICredentials { Identifier = "username", SessionToken = "session_token" }; var client = new OCMClient(baseUrl, apiKey); client.UpdatePOI(poi, credentials); ``` -------------------------------- ### Get Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/ocmclient.md A generic method to call any arbitrary API endpoint. Use this for accessing specific or less common API functionalities not covered by dedicated methods. ```APIDOC ## Get ### Description Generic method to call any API endpoint. ### Method GET (Implied) ### Endpoint /{endpoint} ### Parameters #### Path Parameters - **endpoint** (string) - Required - Relative endpoint path (e.g., `/referencedata?client=ocm.api.client&output=json`) ### Response #### Success Response (200) - **object** (string) - Raw response as string #### Response Example ```json "Raw API response string" ``` ``` -------------------------------- ### Mount Custom appsettings.json for Configuration Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Mounts a local `appsettings.Production.json` file into the container to override default application settings. Ensure the file exists at the specified host path. ```bash -v /path/to/your/appsettings.Production.json:/app/appsettings.Production.json ``` -------------------------------- ### Get Fastest Chargers Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/README.md Retrieves charging stations based on location and a minimum power output (kW). Ideal for finding high-speed charging options. ```csharp var filter = new APIRequestParams { Latitude = lat, Longitude = lng, Distance = 50, DistanceUnit = DistanceUnit.KM, MinPowerKW = 100, // 100 kW or higher MaxResults = 50 }; ``` -------------------------------- ### Get System Status Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/ocmclient.md Retrieve system status information, including cache status and data freshness. Returns system information or null on failure. ```csharp public async Task GetSystemStatusAsync() ``` ```csharp var status = await client.GetSystemStatusAsync(); Console.WriteLine($"System Version: {status.SystemVersion}"); Console.WriteLine($"Latest POI Updated: {status.POIDataLastModified}"); Console.WriteLine($"Max POI ID: {status.MaxPOIId}"); ``` -------------------------------- ### Initialize APIRequestParams Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/configuration.md Initializes the APIRequestParams object with default values for various configuration options. These defaults simplify initial setup for common search scenarios. ```csharp public APIRequestParams() ``` -------------------------------- ### Build Language Packs Source: https://github.com/openchargemap/ocm-system/blob/master/Localisation/readme.md Run 'grunt' in the /Localisation/ directory to build JavaScript files, language packs, and copy build output to other OCM projects. ```bash grunt ``` -------------------------------- ### Stop and Start Worker with Docker Compose Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Command to restart services defined in docker-compose.yml, effectively clearing the worker's in-memory failed imports cache. ```bash docker-compose restart ``` -------------------------------- ### Tag and Push Docker Image Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Tags the local Docker image with a registry-specific tag and pushes it to the specified registry. ```bash # Tag image docker tag ocm-import-worker:latest myregistry.azurecr.io/ocm-import-worker:v1.0.0 # Login to registry docker login myregistry.azurecr.io # Push image docker push myregistry.azurecr.io/ocm-import-worker:v1.0.0 ``` -------------------------------- ### Fetch Data Providers from API Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Command to retrieve a list of data providers from the OCM API, including their ID, Title, and DateLastImported. ```bash curl "https://api-01.openchargemap.io/v3/referencedata/" | jq '.DataProviders[] | {ID, Title, DateLastImported}' ``` -------------------------------- ### Search for Open Data Locations with Media Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Query for charging locations that are part of the open data initiative and have associated media items. ```bash # Open-data locations with photos curl "https://api.openchargemap.org/v4/poi?latitude=51.5074&longitude=-0.1278&distance=10&opendata=true&hasmedia=true" ``` -------------------------------- ### Get POI List with Filters Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/ocmclient.md Query the POI database using search filters for location and attributes. Returns a list of matching ChargePoint objects or null on failure. ```csharp public async Task> GetPOIListAsync(SearchFilters filters) ``` ```csharp var filters = new SearchFilters { Latitude = 51.5074, Longitude = -0.1278, Distance = 5, DistanceUnit = DistanceUnit.Miles, MaxResults = 50, IncludeUserComments = true }; var pois = await client.GetPOIListAsync(filters); foreach (var poi in pois) { Console.WriteLine($"OCM-{poi.ID}: {poi.AddressInfo.Title}"); Console.WriteLine($" Location: {poi.AddressInfo.Latitude}, {poi.AddressInfo.Longitude}"); if (poi.Connections != null) { foreach (var conn in poi.Connections) { Console.WriteLine($" - {conn.ConnectionType?.Title} ({conn.PowerKW}kW)"); } } } ``` -------------------------------- ### Query Flow Diagram Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/architecture.md Illustrates the sequence of operations for a read request, from client to database and back. ```text Client Request ↓ OCMClient.GetPOIListAsync(filters) ↓ SearchFilters → APIRequestParams (serialized to URL) ↓ HTTP GET /v4/poi?latitude=...&longitude=... ↓ POIController.Get() ↓ ParseParameters() → APIRequestParams object ↓ POIManager.GetPOIListAsync(filter) ↓ ApplyQueryFilters() to IQueryable ↓ [Branch: AllowMirrorDB] → CacheProviderMongoDB.Query() [Branch: AllowDataStoreDB] → OCMEntities.ChargePoints.Where() ↓ Populate reference data (DataProvider, OperatorInfo, etc.) ↓ FromDataModel() → API model ChargePoint objects ↓ JsonSerializer.Serialize() → JSON response ↓ HTTP 200 + JSON array ↓ OCMClient deserializes JSON → List ↓ Application uses data ``` -------------------------------- ### GET /v4/poi Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Query charging locations with various geographic and attribute filters. This endpoint allows for flexible searching of charging stations based on location, power, connection types, and more. ```APIDOC ## GET /v4/poi ### Description Query charging locations with geographic and attribute filters. ### Method GET ### Endpoint /v4/poi ### Parameters #### Query Parameters - **latitude** (double) - Optional - Center latitude for distance search (-90 to 90) - **longitude** (double) - Optional - Center longitude for distance search (-180 to 180) - **distance** (double) - Optional - Search radius in specified distance unit (default: 10) - **distanceunit** (string) - Optional - Distance unit: `km` or `miles` (default: miles) - **maxresults** (int) - Optional - Maximum results to return (0-10000) (default: 100) - **countryid** (comma-separated ints) - Optional - Filter by country IDs - **operatorid** (comma-separated ints) - Optional - Filter by operator/network IDs - **connectiontypeid** (comma-separated ints) - Optional - Filter by connection type IDs - **levelid** (comma-separated ints) - Optional - Filter by charging level IDs - **usagetypeid** (comma-separated ints) - Optional - Filter by usage type IDs - **statustypeid** (comma-separated ints) - Optional - Filter by operational status IDs - **dataproviderid** (comma-separated ints) - Optional - Filter by data provider IDs - **submissionstatustypeid** (comma-separated ints) - Optional - Filter by publication status (defaults to published) - **minpowerkw** (double) - Optional - Minimum power output in kW (fast chargers: 50+) - **maxpowerkw** (double) - Optional - Maximum power output in kW - **opendata** (boolean) - Optional - Filter to open-licensed data only (true/false) - **hasmedia** (boolean) - Optional - Only locations with photos (true/false) - **hascomment** (boolean) - Optional - Only locations with user comments (true/false) - **hascheckins** (boolean) - Optional - Only locations with check-ins (true/false) - **includecomments** (boolean) - Optional - Include user comments in response (default: false) - **verbose** (boolean) - Optional - Include extended object details (default: true) - **compact** (boolean) - Optional - Minimize response (legacy) (default: false) - **camelcase** (boolean) - Optional - Use camelCase property names (default: false) - **modifiedsince** (ISO 8601) - Optional - Only POIs modified after date (e.g., `2024-01-15T00:00:00Z`) - **createdsince** (ISO 8601) - Optional - Only POIs created after date - **greaterthanid** (int) - Optional - Only POIs with ID greater than value (batch imports) - **sortby** (string) - Optional - Sort order: `created_asc`, `modified_asc`, `id_asc` - **levelofdetail** (int) - Optional - Random sampling (higher = fewer results) - **enablecaching** (boolean) - Optional - Use cached data when available (default: true) - **allowmirror** (boolean) - Optional - Query MongoDB mirror cache (default: true) - **excludecomputed** (boolean) - Optional - Exclude computed properties (default: false) - **apikey** (string) - Optional - API key (alternative: X-API-Key header) - **callback** (string) - Optional - JSONP callback function name #### Geographic Filters (Advanced) - **polyline** (string) - Google-encoded polyline (e.g., route coordinates) - **boundingbox** (string) - Bounding box format: `(lat1,lon1),(lat2,lon2)` - **polygon** (string) - Polygon vertices: `(lat1,lon1),(lat2,lon2),...` ``` -------------------------------- ### POIManager.GetFullDetails Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/managers.md A convenience method to retrieve a complete POI, including all associated reference data. This is equivalent to calling the `Get` method with `includeExtendedInfo` set to true and `allowMirrorDB` set to true. ```APIDOC ## POIManager.GetFullDetails ### Description Convenience method equivalent to `Get(id, true, false, true)`. Retrieves complete POI with all reference data. ### Method `public async Task GetFullDetails(int id)` ### Parameters #### Path Parameters - **id** (int) - Required - POI ID to retrieve ### Response #### Success Response - **Model.ChargePoint** - Fully populated POI ``` -------------------------------- ### Get Single POI by ID Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/managers.md Retrieves a single charging location (POI) by its unique identifier. Can optionally include extended information and utilize disk or mirror database caching. ```csharp public async Task Get(int id) public async Task Get( int id, bool includeExtendedInfo, bool allowDiskCache = false, bool allowMirrorDB = false ) ``` -------------------------------- ### Debugging RWE-Mobility Import with RuntimeBinderException Source: https://github.com/openchargemap/ocm-system/blob/master/Import/import-debug-log.txt This log indicates an import failure from RWE-Mobility.com due to a RuntimeBinderException, specifically when attempting to perform runtime binding on a null reference. This often points to issues with dynamic object processing or missing data. ```text [RWE-Mobility.com]: Country Not Matched, will require Geolocation:Czechoslovakia A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll [RWE-Mobility.com]: Import Failed:RWE-Mobility.com ::Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference at CallSite.Target(Closure , CallSite , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0) at CallSite.Target(Closure , CallSite , Object ) at OCM.Import.Providers.ImportProvider_RWEMobility.Process(CoreReferenceData coreRefData) in c:\\Temp\\GIT\\projects\\ocm-system\\Import\\OCM.Import.Common\\Providers\\ImportProvider_RWEMobility.cs:line 84 at OCM.Import.ImportManager.PerformImportProcessing(ExportType exportType, String defaultDataPath, String apiIdentifier, String apiSessionToken, Boolean fetchLiveData) in c:\\Temp\\GIT\\projects\\ocm-system\\Import\\OCM.Import.Common\\ImportManager.cs:line 341 ``` -------------------------------- ### Get Core Reference Data Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/ocmclient.md Retrieve essential reference data such as connection types, countries, and operators. This method returns a complete reference data object or null on failure. ```csharp public async Task GetCoreReferenceDataAsync() ``` ```csharp using var client = new OCMClient("https://api.openchargemap.org/v3", apiKey); var refData = await client.GetCoreReferenceDataAsync(); if (refData != null) { foreach (var country in refData.Countries) { Console.WriteLine($"{country.Title} ({country.ID})"); } } ``` -------------------------------- ### REST API Query for Charging Locations Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/README.md Example using curl to query charging locations near London with specific filters like distance, minimum power, and maximum results. ```bash # Query charging locations near London, 5 miles, 50+ kW curl -H "X-API-Key: YOUR_API_KEY" \ "https://api.openchargemap.org/v4/poi?latitude=51.5074&longitude=-0.1278&distance=5&distanceunit=miles&minpowerkw=50&maxresults=100" ``` -------------------------------- ### Pull and Run Docker Image Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Pulls a Docker image from a registry and runs it as a detached container. ```bash # Pull image docker pull myregistry.azurecr.io/ocm-import-worker:v1.0.0 # Run pulled image docker run -d myregistry.azurecr.io/ocm-import-worker:v1.0.0 ``` -------------------------------- ### Monitor Container in Real-time Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Displays real-time resource usage statistics (CPU, memory, network I/O, etc.) for the ocm-import-worker container. ```bash # Monitor in real-time docker stats ocm-import-worker ``` -------------------------------- ### Run OCM Import Worker in Background with Auto-Restart Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Starts the OCM Import Worker container in detached mode with an automatic restart policy. This is suitable for production deployments where continuous operation is required. ```bash # Run in background with auto-restart docker run -d \ --name ocm-import-worker \ --restart unless-stopped \ ocm-import-worker:latest ``` -------------------------------- ### Verify Environment Variables Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Executes the 'env' command inside the container and filters for DOTNET environment variables to verify configuration. ```bash # Verify environment variables docker exec ocm-import-worker env | grep DOTNET ``` -------------------------------- ### Check for Blocked Providers Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Use this Docker command to inspect the logs of the ocm-import-worker and identify if providers are being blocked due to recent failures. ```bash # Check if providers are blocked docker logs ocm-import-worker | grep "blocked by recent failures" ``` -------------------------------- ### Scaffold Entity Framework Core DbContext Source: https://github.com/openchargemap/ocm-system/blob/master/API/OCM.Net/OCM.API.Core/DataModelRefresh.txt Use this command to scaffold a DbContext from an existing SQL Server database. Ensure the correct server, database, and context name are provided. ```powershell Scaffold-DbContext "Server=(local)\SQLEXPRESS;Database=OCM_Live;Trusted_Connection=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data -Force -Context OCMEntities ``` -------------------------------- ### View Worker Logs (Systemd) Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/SCHEDULING.md Command to view and follow logs for the OCM import worker service when managed by systemd. ```bash journalctl -u ocm-import-worker -f ``` -------------------------------- ### API Key Authentication Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Demonstrates how to authenticate API requests using an API key, either as a query parameter or a request header. ```APIDOC ## API Key Authentication ### Description Some operations require authentication via API key. The API key can be provided either as a query parameter or as a request header. ### Method GET ### Endpoint `/v4/poi` ### Parameters #### Query Parameters - **apikey** (string) - Required - Your API key for authentication. #### Request Header - **X-API-Key** (string) - Required - Your API key for authentication. ### Request Example ```bash # Query parameter curl "https://api.openchargemap.org/v4/poi?apikey=YOUR_API_KEY" # Request header (preferred) curl -H "X-API-Key: YOUR_API_KEY" "https://api.openchargemap.org/v4/poi" ``` ``` -------------------------------- ### Get Complete Reference Data (Synchronous) Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/managers.md Synchronously retrieves the complete set of reference data, potentially filtered by the provided APIRequestParams. Used for obtaining lookup data like operators, countries, etc. ```csharp public CoreReferenceData GetCoreReferenceData(APIRequestParams filter) ``` -------------------------------- ### Get Distance in Kilometers (SQL Function) Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/managers.md Entity Framework mapping to a SQL Server User-Defined Function (udf_GetDistanceFromLatLonKM) for calculating distances between two geographical points. Primarily used within LINQ queries. ```csharp [DbFunction("OCM.Core.Data.OCMEntities.Store", "udf_GetDistanceFromLatLonKM")] public static double? GetDistanceFromLatLonKM( double? Latitude1, double? Longitude1, double? Latitude2, double? Longitude2 ) ``` -------------------------------- ### Compact JSON Output Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/endpoints.md Demonstrates how to request a minimized JSON response that excludes null properties. ```bash curl "https://api.openchargemap.org/v4/poi?compact=true" ``` -------------------------------- ### OCM Import Worker Docker Compose Configuration Source: https://github.com/openchargemap/ocm-system/blob/master/Import/OCM.Import.Worker/DOCKER.md Example Docker Compose configuration for the OCM Import Worker service, including image, restart policy, environment variables, resource limits, and logging settings. ```yaml services: ocm-import-worker: image: ocm-import-worker:latest restart: unless-stopped environment: - DOTNET_ENVIRONMENT=Production - KeyVaultName=${AZURE_KEYVAULT_NAME} - AZURE_CLIENT_ID=${AZURE_CLIENT_ID} - AZURE_CLIENT_SECRET=${AZURE_CLIENT_SECRET} - AZURE_TENANT_ID=${AZURE_TENANT_ID} deploy: resources: limits: cpus: '2.0' memory: 4G reservations: cpus: '0.5' memory: 1G logging: driver: "json-file" options: max-size: "10m" max-file: "3" healthcheck: test: ["CMD", "test", "-f", "/app/OCM.Import.Worker.dll"] interval: 30s timeout: 5s retries: 3 ``` -------------------------------- ### Get Core Reference Data Source: https://github.com/openchargemap/ocm-system/blob/master/_autodocs/api-reference/core-models.md Fetches all available reference data, including countries, operators, connection types, and more. This data is used to populate UI elements like dropdowns and to validate user input during POI submissions. ```csharp var refData = await client.GetCoreReferenceDataAsync(); var ccsConnectors = refData.ConnectionTypes .Where(ct => ct.Title.Contains("CCS")) .ToList(); var fastChargers = refData.ChargerTypes .Where(ct => ct.Title.Contains("DC")) .ToList(); ```