### Client Service Instance Setup Source: https://context7.com/chrizog/someipy/llms.txt Imports necessary components for setting up a client-side SOME/IP service instance. This code is a starting point for consuming remote services and subscribing to events. ```python import asyncio import logging from someipy import ( ClientServiceInstance, ServiceBuilder, EventGroup, Event, TransportLayerProtocol, connect_to_someipy_daemon, ) from someipy.someipy_logging import set_someipy_log_level ``` -------------------------------- ### Server Service Instance Example Source: https://context7.com/chrizog/someipy/llms.txt Sets up and runs a server-side SOME/IP service instance. It defines a service with events, creates a service instance, starts offering it, and continuously sends events. Ensure the SOME/IP daemon is running. ```python import asyncio import logging from someipy import ( ServerServiceInstance, ServiceBuilder, EventGroup, Event, TransportLayerProtocol, connect_to_someipy_daemon, ) from someipy.someipy_logging import set_someipy_log_level from someipy.serialization import Uint8, Uint64, Float32 # Define payload structure from dataclasses import dataclass from someipy.serialization import SomeIpPayload, SomeIpFixedSizeArray @dataclass class TemperatureMsg(SomeIpPayload): timestamp: Uint64 measurements: SomeIpFixedSizeArray def __init__(self): self.timestamp = Uint64() self.measurements = SomeIpFixedSizeArray(Float32, 4) SAMPLE_SERVICE_ID = 0x1234 SAMPLE_INSTANCE_ID = 0x5678 SAMPLE_EVENTGROUP_ID = 0x0321 SAMPLE_EVENT_ID = 0x0123 async def main(): set_someipy_log_level(logging.DEBUG) someipy_daemon = await connect_to_someipy_daemon() # Define the service temperature_event = Event(id=SAMPLE_EVENT_ID, protocol=TransportLayerProtocol.UDP) temperature_eventgroup = EventGroup(id=SAMPLE_EVENTGROUP_ID, events=[temperature_event]) temperature_service = ( ServiceBuilder() .with_service_id(SAMPLE_SERVICE_ID) .with_major_version(1) .with_eventgroup(temperature_eventgroup) .build() ) # Create server service instance service_instance = ServerServiceInstance( daemon=someipy_daemon, service=temperature_service, instance_id=SAMPLE_INSTANCE_ID, endpoint_ip="127.0.0.1", endpoint_port=3000, ttl=5, cyclic_offer_delay_ms=2000, ) # Start offering the service print("Start offering service...") await service_instance.start_offer() # Prepare and send events tmp_msg = TemperatureMsg() tmp_msg.measurements.data[0] = Float32(20.0) tmp_msg.measurements.data[1] = Float32(21.0) tmp_msg.measurements.data[2] = Float32(22.0) tmp_msg.measurements.data[3] = Float32(23.0) try: while True: await asyncio.sleep(1) tmp_msg.timestamp = Uint64(tmp_msg.timestamp.value + 1) payload = tmp_msg.serialize() # Send event to all subscribed clients service_instance.send_event(SAMPLE_EVENTGROUP_ID, SAMPLE_EVENT_ID, payload) print(f"Sent event with timestamp: {tmp_msg.timestamp.value}") except asyncio.CancelledError: print("Stopping service...") await service_instance.stop_offer() finally: await someipy_daemon.disconnect_from_daemon() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Start the someipy Daemon with Configuration Source: https://github.com/chrizog/someipy/blob/master/docs/someipy_daemon.md Start the someipy daemon and specify a custom configuration file using the --config argument. ```bash someipyd --config /path/to/config.json ``` -------------------------------- ### start_offer Method Source: https://github.com/chrizog/someipy/blob/master/docs/api/server_service_instance.md Starts offering the service instance by advertising it through the service discovery mechanism. ```APIDOC ## start_offer ### Description Start offering the service instance via the service discovery offer entries. This method gathers the current service methods and event groups and invokes the daemon to advertise the service with the configured endpoint and version information. ### Returns None ``` -------------------------------- ### Start the someipy Daemon Source: https://github.com/chrizog/someipy/blob/master/docs/someipy_daemon.md Run this command in your terminal to start the someipy daemon. Ensure the library is installed via 'pip3 install someipy'. ```bash someipyd ``` -------------------------------- ### Build and Start SOME/IP Server Source: https://context7.com/chrizog/someipy/llms.txt Build a SOME/IP service using ServiceBuilder, add methods to it, and then create and start a ServerServiceInstance to offer the service. Ensure proper disconnection from the daemon in a finally block. ```python import asyncio import logging from someipy import (ServiceBuilder, Method, TransportLayerProtocol) from someipy.someipy_logging import set_someipy_log_level from someipy.daemon import connect_to_someipy_daemon from someipy.server import ServerServiceInstance # Assume SAMPLE_METHOD_ID, addition_method_handler are defined elsewhere SAMPLE_SERVICE_ID = 0x1234 SAMPLE_INSTANCE_ID = 0x5678 async def main(): set_someipy_log_level(logging.DEBUG) someipy_daemon = await connect_to_someipy_daemon() # Create method with handler addition_method = Method( id=SAMPLE_METHOD_ID, protocol=TransportLayerProtocol.UDP, method_handler=add_method_handler, ) # Build service with method addition_service = ( ServiceBuilder() .with_service_id(SAMPLE_SERVICE_ID) .with_major_version(1) .with_method(addition_method) .build() ) # Create and start server instance server_instance = ServerServiceInstance( daemon=someipy_daemon, service=addition_service, instance_id=SAMPLE_INSTANCE_ID, endpoint_ip="127.0.0.1", endpoint_port=3000, ttl=5, cyclic_offer_delay_ms=2000, ) print("Start offering method service...") await server_instance.start_offer() try: await asyncio.Future() # Keep the server running except asyncio.CancelledError: await server_instance.stop_offer() finally: await someipy_daemon.disconnect_from_daemon() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Start the someipy Daemon Source: https://context7.com/chrizog/someipy/llms.txt Start the someipy daemon process, which manages network communication and service discovery. It can be started with default settings or a custom configuration file. ```bash # Start with default configuration someipyd ``` ```bash # Start with custom configuration file someipyd --config /path/to/config.json ``` -------------------------------- ### Start the someipy Daemon Source: https://github.com/chrizog/someipy/blob/master/docs/getting_started.md Ensure the someipy daemon is running before executing your application. Start it using the 'someipyd' command, optionally providing a configuration file. ```bash someipyd --config someipyd.json ``` -------------------------------- ### Setup Python Pip Package from Source Source: https://github.com/chrizog/someipy/blob/master/integration_tests/README.md Install the Python package in editable mode using pip. This is useful for development. ```bash python3 -m pip install -e . ``` -------------------------------- ### Run the Application Source: https://github.com/chrizog/someipy/blob/master/docs/getting_started.md Execute your Python application using the 'python3' command to start the SOME/IP service and event sending. ```bash python3 send_events_udp.py ``` -------------------------------- ### Server-Side Service Instance Configuration Source: https://github.com/chrizog/someipy/blob/master/docs/service_discovery.md Python example for configuring a server-side service instance with SOME/IP SD parameters. Sets the Time-To-Live (TTL) for offer entries and the delay between cyclic offer messages. ```python service_instance_temperature = ServerServiceInstance( daemon=someipy_daemon, service=temperature_service, instance_id=SAMPLE_INSTANCE_ID, endpoint_ip=interface_ip, endpoint_port=3000, ttl=5, cyclic_offer_delay_ms=2000, ) ``` -------------------------------- ### Network Setup for Linux Source: https://github.com/chrizog/someipy/blob/master/integration_tests/README.md Configure network interfaces on Linux for testing. This includes setting a static IP and joining a multicast group. ```bash sudo ip addr add 127.0.0.2/8 dev lo sudo ip addr add 224.224.224.245 dev lo autojoin ``` -------------------------------- ### Install someipy Package Source: https://github.com/chrizog/someipy/blob/master/README.md Install the someipy package using pip. This command is used to add the library to your Python environment. ```bash pip3 install someipy ``` -------------------------------- ### Build Test Applications with CMake Source: https://github.com/chrizog/someipy/blob/master/integration_tests/README.md Use this command to clean, build, and install test applications using CMake. Ensure you are in the build directory. ```bash rm -rf build install && mkdir -p build && cd build && cmake .. && make && make install && cd .. ``` -------------------------------- ### someipy Daemon Configuration Example Source: https://github.com/chrizog/someipy/blob/master/docs/someipy_daemon.md A JSON configuration file for the someipy daemon. All fields are optional and customize daemon behavior such as service discovery, logging, and network interface settings. ```json { "sd_address": "224.224.224.245", "sd_port": 30490, "log_level": "DEBUG", "interface": "127.0.0.2", "log_path": "/var/log/someipy.log", "use_tcp": false, "tcp_host": "127.0.0.1", "tcp_port": 30500 } ``` -------------------------------- ### Configure Network Interface for Multicast Source: https://github.com/chrizog/someipy/blob/master/docs/getting_started.md On Linux, join the multicast group for your network interface using 'ip addr add' before starting the application to enable client subscriptions. Adjust the multicast address and interface as needed. ```bash sudo ip addr add 224.224.224.245 dev lo autojoin python3 send_events_udp.py ``` -------------------------------- ### Client-Side Eventgroup Subscription Source: https://github.com/chrizog/someipy/blob/master/docs/service_discovery.md Python example for a client subscribing to a SOME/IP eventgroup. Sets the subscription lifetime in seconds, which determines how long the subscription remains active if not renewed. ```python service_instance_temperature.subscribe_eventgroup(temperature_eventgroup, ttl_subscription_seconds=5.0) ``` -------------------------------- ### vsomeip3 CMakeLists.txt Configuration Source: https://github.com/chrizog/someipy/blob/master/integration_tests/CMakeLists.txt Configures the CMake build system for vsomeip3 applications. It sets the minimum CMake version, project name, build type, C++ standard, finds the vsomeip3 package, and defines installation prefixes. ```cmake cmake_minimum_required (VERSION 3.13) project(someipy_test_apps) set(CMAKE_BUILD_TYPE Debug) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") find_package(vsomeip3 CONFIG REQUIRED) set(CMAKE_INSTALL_PREFIX "${CMAKE_SOURCE_DIR}/install") function(create_test_target target_name) add_executable(${target_name} ${target_name}/${target_name}.cpp) target_link_libraries(${target_name} ${VSOMEIP_LIBRARIES} pthread) install(TARGETS ${target_name} RUNTIME DESTINATION ${target_name}) file(GLOB ADDITIONAL_FILES "${CMAKE_SOURCE_DIR}/${target_name}/*.json" "${CMAKE_SOURCE_DIR}/${target_name}/*.sh") install(FILES ${ADDITIONAL_FILES} DESTINATION ${target_name}) endfunction() # The same app can be used for UDP and TCP for the "send_events" example app create_test_target("send_events") create_test_target("receive_events_udp") create_test_target("receive_events_tcp") create_test_target("offer_method_udp") create_test_target("offer_method_tcp") create_test_target("call_method_udp") create_test_target("call_method_tcp") create_test_target("offer_multiple_services") ``` -------------------------------- ### Define SOME/IP Service with EventGroup Source: https://github.com/chrizog/someipy/blob/master/docs/getting_started.md Define a SOME/IP service using `ServiceBuilder`. This example creates a service with ID 0x1234, version 1.0, and an event group (0x0321) containing a single UDP event (0x0123). ```python from someipy import ServiceBuilder, EventGroup async def main(): # ... SAMPLE_SERVICE_ID = 0x1234 SAMPLE_EVENTGROUP_ID = 0x0321 SAMPLE_EVENT_ID = 0x0123 temperature_event = Event(id=SAMPLE_EVENT_ID, protocol=TransportLayerProtocol.UDP) temperature_eventgroup = EventGroup( id=SAMPLE_EVENTGROUP_ID, events=[temperature_event] ) temperature_service = ( ServiceBuilder() .with_service_id(SAMPLE_SERVICE_ID) .with_major_version(1) .with_eventgroup(temperature_eventgroup) .build() ) # ... ``` -------------------------------- ### Build and Run SOME/IP Client Source: https://context7.com/chrizog/someipy/llms.txt This Python script demonstrates a complete SOME/IP client. It connects to the daemon, defines a service method, creates a client instance, and repeatedly calls the method, handling responses and errors. ```python import asyncio import logging from someipy.core import ( ServiceBuilder, Method, ClientServiceInstance, MessageType, ReturnCode ) from someipy.transport import TransportLayerProtocol from someipy.someipy_logging import set_someipy_log_level # Assume Addends, Sum, SAMPLE_SERVICE_ID, SAMPLE_INSTANCE_ID, SAMPLE_METHOD_ID are defined as above async def main(): set_someipy_log_level(logging.DEBUG) someipy_daemon = await connect_to_someipy_daemon() addition_method = Method( id=SAMPLE_METHOD_ID, protocol=TransportLayerProtocol.UDP, ) addition_service = ( ServiceBuilder() .with_service_id(SAMPLE_SERVICE_ID) .with_major_version(1) .with_method(addition_method) .build() ) client_instance = ClientServiceInstance( daemon=someipy_daemon, service=addition_service, instance_id=SAMPLE_INSTANCE_ID, endpoint_ip="127.0.0.1", endpoint_port=3002, ) try: print("Waiting for service to be available...") while not await client_instance.is_available(): await asyncio.sleep(0.5) print("Service found!") method_params = Addends(addend1=10, addend2=25) while True: try: print(f"Calling method with: {method_params.addend1.value} + {method_params.addend2.value}") method_result = await client_instance.call_method( SAMPLE_METHOD_ID, method_params.serialize() ) if method_result.message_type == MessageType.RESPONSE: if method_result.return_code == ReturnCode.E_OK: sum_result = Sum().deserialize(method_result.payload) print(f"Result: {sum_result.value.value}") else: print(f"Method error: {method_result.return_code}") elif method_result.message_type == MessageType.ERROR: print("Server returned an error") except asyncio.TimeoutError: print("Method call timed out") except RuntimeError as e: print(f"Service not available: {e}") await asyncio.sleep(2) except asyncio.CancelledError: print("Shutting down...") finally: await someipy_daemon.disconnect_from_daemon() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Instantiate a Client Service Instance Source: https://github.com/chrizog/someipy/blob/master/docs/calling_methods.md Create a client instance for a specific service. This requires the connected daemon, the service definition, a unique instance ID, and the endpoint details (IP and port) of the service. ```python from someip_python.client import ClientServiceInstance SAMPLE_INSTANCE_ID = 0x5678 interface_ip = "127.0.0.1" client_instance_addition = ClientServiceInstance( daemon=someipy_daemon, service=addition_service, instance_id=SAMPLE_INSTANCE_ID, endpoint_ip=interface_ip, endpoint_port=3002, ) ``` -------------------------------- ### Get SomeIP Log Level Source: https://github.com/chrizog/someipy/blob/master/docs/api/someipy_logging.md Retrieves the current logging level configured for the someipy library. ```APIDOC ## GET /someipy/logging/level ### Description Get the current log level for the someipy library. ### Method GET ### Endpoint /someipy/logging/level ### Response #### Success Response (200) - **logging_level** (int) - The current log level. ``` -------------------------------- ### Announce Service Instance via Service Discovery Source: https://github.com/chrizog/someipy/blob/master/docs/offering_methods.md Use `start_offer` to announce the service instance to potential clients. This function communicates with the someipy daemon to periodically send service discovery messages. ```python await service_instance_addition.start_offer() ``` -------------------------------- ### Instantiate ServerServiceInstance Source: https://github.com/chrizog/someipy/blob/master/docs/getting_started.md Use ServerServiceInstance to offer a SOME/IP service. Ensure the someipy_daemon, Service object, and necessary network details are provided. Call start_offer() to begin advertising the service and stop_offer() when exiting. ```python from someipy import TransportLayerProtocol, construct_server_service_instance async def main(): # ... SAMPLE_INSTANCE_ID = 0x5678 service_instance_temperature = ServerServiceInstance( daemon=someipy_daemon, service=temperature_service, instance_id=SAMPLE_INSTANCE_ID, endpoint_ip=interface_ip, endpoint_port=3000, ttl=5, cyclic_offer_delay_ms=2000, ) # After constructing a ServerServiceInstances the start_offer method has to be called. This will start an internal timer, # which will periodically send Offer service entries with a period of "cyclic_offer_delay_ms" which has been passed above print("Start offering service..") await service_instance_temperature.start_offer() # ... # Before exiting the app: service_instance_temperature.stop_offer() ``` -------------------------------- ### Defining a Structured SOME/IP Datatype Source: https://github.com/chrizog/someipy/blob/master/docs/service_interface.md Define a custom structured SOME/IP data type by subclassing SomeIpPayload and using dataclasses. This example defines a TemperatureMsg with a timestamp and temperature field. ```python from dataclasses import dataclass from someipy.serialization import ( SomeIpPayload, Uint64, Float32, ) @dataclass class TemperatureMsg(SomeIpPayload): timestamp: Uint64 temperature: Float32 def __init__(self): self.timestamp = Uint64() self.temperature = Float32() ``` -------------------------------- ### Announce Service via Service Discovery Source: https://github.com/chrizog/someipy/blob/master/docs/offering_events.md Use start_offer to make the service instance discoverable by clients. This function communicates with the someipy daemon to periodically send service discovery messages. ```python await service_instance_temperature.start_offer() ``` -------------------------------- ### Instantiate a Server Service Instance Source: https://github.com/chrizog/someipy/blob/master/docs/offering_methods.md This code instantiates a ServerServiceInstance to offer a defined SOME/IP service on a specific network interface and port. Configure parameters like daemon, service, instance_id, endpoint details, TTL, and offer delay. ```python SAMPLE_INSTANCE_ID = 0x5678 service_instance_addition = ServerServiceInstance( daemon=someipy_daemon, service=addition_service, instance_id=SAMPLE_INSTANCE_ID, endpoint_ip=interface_ip, endpoint_port=3000, ttl=5, cyclic_offer_delay_ms=2000, ) ``` -------------------------------- ### Define Temperature Message Structure Source: https://github.com/chrizog/someipy/blob/master/docs/getting_started.md Define custom data structures for SOME/IP messages using Python dataclasses. This example defines a 'Version' and 'TemperatureMsg' structure, including nested types and fixed-size arrays. ```python from dataclasses import dataclass from someipy.serialization import ( SomeIpPayload, SomeIpFixedSizeArray, Uint8, Uint64, Float32, ) @dataclass class Version(SomeIpPayload): major: Uint8 minor: Uint8 def __init__(self): self.major = Uint8() self.minor = Uint8() @dataclass class TemperatureMsg(SomeIpPayload): version: Version timestamp: Uint64 measurements: SomeIpFixedSizeArray def __init__(self): self.version = Version() self.timestamp = Uint64() self.measurements = SomeIpFixedSizeArray(Float32, 4) ``` -------------------------------- ### Basic Asyncio Application Structure Source: https://github.com/chrizog/someipy/blob/master/docs/getting_started.md Set up the basic structure for an asyncio application using `asyncio.run` and a main coroutine function. Includes basic exception handling for cancellation and keyboard interrupts. ```python import asyncio import ipaddress import logging async def main(): # .. our application will go here except asyncio.CancelledError: print("Application cancelled...") finally: print("Cleanup...") print("End main task...") if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: pass ``` -------------------------------- ### Construct Client Service Instance Source: https://github.com/chrizog/someipy/blob/master/docs/whatsnew.md Creates an instance of a client service for interacting with a specific SOME/IP service. Requires the daemon connection, service definition, instance ID, and endpoint details. ```python client_instance_addition = ClientServiceInstance( daemon=someipy_daemon, service=addition_service, instance_id=SAMPLE_INSTANCE_ID, endpoint_ip=interface_ip, endpoint_port=3002, ) ``` -------------------------------- ### Implement SOME/IP Server Methods Source: https://context7.com/chrizog/someipy/llms.txt This code sets up a SOME/IP server that offers methods for request-response communication. The method handler is an async function that receives request bytes and returns a MethodResult. ```python import asyncio import logging from typing import Tuple from dataclasses import dataclass from someipy import ( ServerServiceInstance, ServiceBuilder, Method, MethodResult, MessageType, ReturnCode, TransportLayerProtocol, connect_to_someipy_daemon, ) from someipy.someipy_logging import set_someipy_log_level from someipy.serialization import SomeIpPayload, Sint16, Sint32 ``` -------------------------------- ### Build a Service with Events and Methods Source: https://context7.com/chrizog/someipy/llms.txt Constructs a SOME/IP service definition using ServiceBuilder, including service ID, version, event groups, and methods. This is a foundational step before creating a service instance. ```python my_service = ( ServiceBuilder() .with_service_id(SAMPLE_SERVICE_ID) .with_major_version(1) .with_minor_version(0) .with_eventgroup(temperature_eventgroup) .with_method(addition_method) .build() ) ``` -------------------------------- ### Call SOME/IP Method with Parameters Source: https://github.com/chrizog/someipy/blob/master/docs/calling_methods.md Prepare method parameters, serialize them, and call the method on a client service instance. Await the result, check message type and return code, and deserialize the payload. Handles potential exceptions like RuntimeError or asyncio.TimeoutError. ```python method_parameter = Addends(addend1=1, addend2=2) while True: try: method_result = await client_instance_addition.call_method( SAMPLE_METHOD_ID, method_parameter.serialize() ) if method_result.message_type == MessageType.RESPONSE: print( f"Received result for method: {' '.join(f'0x{b:02x}' for b in method_result.payload)}" ) if method_result.return_code == ReturnCode.E_OK: sum = Sum().deserialize(method_result.payload) print(f"Sum: {sum.value.value}") else: print( f"Method call returned an error: {method_result.return_code}" ) elif method_result.message_type == MessageType.ERROR: print("Server returned an error..") # In case the server includes an error message in the payload, it can be deserialized and printed except Exception as e: print(f"Error during method call: {e}") ``` -------------------------------- ### Configure Network for SOME/IP Service Discovery (Linux) Source: https://context7.com/chrizog/someipy/llms.txt Join the necessary multicast group on your network interface before running SOME/IP applications on Linux. This ensures proper service discovery. ```bash # Join multicast group on loopback interface (for local testing) sudo ip addr add 224.224.224.245 dev lo autojoin # Join multicast group on a specific network interface sudo ip addr add 224.224.224.245 dev eth0 autojoin # Start the daemon someipyd --config someipyd.json # Run your application python3 your_someipy_app.py --interface_ip 127.0.0.1 ``` -------------------------------- ### Connect to someipy Daemon Source: https://github.com/chrizog/someipy/blob/master/docs/whatsnew.md Establishes a connection to the someipyd daemon. This is the initial step for any application using the someipy v2 API. ```python someipy_daemon = await connect_to_someipy_daemon() ``` -------------------------------- ### Connect to SomeIPy Daemon Source: https://github.com/chrizog/someipy/blob/master/docs/api/connect_to_someipy_daemon.md Establishes a connection to the SomeIPy daemon. Allows configuration of the socket path. ```APIDOC ## connect_to_someipy_daemon ### Description Connect to the someipy daemon. ### Method ASYNC FUNCTION ### Endpoint N/A (Function Call) ### Parameters #### Request Body - **config** (dict) - Optional - Configuration dictionary. The following keys are supported: - **socket_path** (str) - Optional - Path to the Unix domain socket. Default is /tmp/someipyd.sock ### Response #### Success Response (200) - **SomeIpDaemonClient** (SomeIpDaemonClient) - An instance of the SomeIpDaemonClient class. #### Response Example ```json { "client_instance": "" } ``` ``` -------------------------------- ### someipy.Method Constructor Source: https://github.com/chrizog/someipy/blob/master/docs/api/method.md Initializes a SOME/IP Method object with an ID, protocol, and an optional method handler. ```APIDOC ## someipy.Method(id, protocol, method_handler=None) ### Description Class representing a SOME/IP method with a method id and a method handler. ### Parameters id : Method identifier. protocol : Transport protocol for the method. method_handler : Optional method which is called on server side when an offered service is invoked. The handler shall return a MethodResult. ### Attributes id *: int* method_handler *: Callable[[bytes, Tuple[str, int]], [MethodResult](method_result.md#someipy.MethodResult)]* protocol *: [TransportLayerProtocol](transport_layer_protocol.md#someipy.TransportLayerProtocol)* ``` -------------------------------- ### ClientServiceInstance Initialization Source: https://github.com/chrizog/someipy/blob/master/docs/api/client_service_instance.md Initializes a ClientServiceInstance to represent a specific SOME/IP service instance on the client side. ```APIDOC ## ClientServiceInstance Constructor ### Description Initializes a client-side representation of a SOME/IP service instance. ### Parameters - **daemon** (SomeIpDaemonClient) - The daemon client instance. - **service** (Service) - The associated Service object. - **instance_id** (int) - The unique identifier for the service instance. - **endpoint_ip** (str) - The IP address of the service instance endpoint. - **endpoint_port** (int) - The port number of the service instance endpoint. - **client_id** (int) - Optional client identifier, defaults to 0. ``` -------------------------------- ### ServerServiceInstance Initialization Source: https://github.com/chrizog/someipy/blob/master/docs/api/server_service_instance.md Initializes a ServerServiceInstance to represent a service instance on the server side for SOME/IP-SD. It requires a daemon client, service configuration, instance ID, and endpoint details. ```APIDOC ## ServerServiceInstance Constructor ### Description Initializes a server-side representation of a service instance for offering SOME/IP services. ### Parameters - **daemon** (Daemon client) - Daemon client used to communicate with the someipy daemon. - **service** (Service configuration) - Service configuration for this instance. - **instance_id** (int) - Instance ID for this service instance. - **endpoint_ip** (str) - IP address of the endpoint on which the service instance is reachable. - **endpoint_port** (int) - Port of the endpoint on which the service instance is reachable. - **ttl** (int) - Optional: TTL used for Service Discovery offers. Default: 0. - **cyclic_offer_delay_ms** (int) - Optional: Delay between cyclic offers in milliseconds. Default: 2000. ``` -------------------------------- ### Connect to the someipy Daemon Source: https://context7.com/chrizog/someipy/llms.txt Establish a connection to the someipy daemon using asyncio. Supports default Unix Domain Sockets (Linux) or custom paths, and TCP sockets for Windows. ```python import asyncio from someipy import connect_to_someipy_daemon async def main(): # Connect using default Unix Domain Socket (Linux) someipy_daemon = await connect_to_someipy_daemon() # Or connect with custom socket path someipy_daemon = await connect_to_someipy_daemon( {"socket_path": "/tmp/custom_someipy.sock"} ) # For Windows, use TCP sockets someipy_daemon = await connect_to_someipy_daemon( {"use_tcp": True, "tcp_host": "127.0.0.1", "tcp_port": 30500} ) # ... your application logic ... # Clean shutdown await someipy_daemon.disconnect_from_daemon() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Connect to someipy Daemon (TCP on Windows) Source: https://github.com/chrizog/someipy/blob/master/docs/getting_started.md Connect to the someipy daemon using TCP sockets, typically required on Windows. Specify the interface IP and optionally the port. ```python someipy_daemon = await connect_to_someipy_daemon( {"use_tcp": True, "tcp_host": interface_ip, "tcp_port": 30500} ) ``` -------------------------------- ### someipy.Method Equality and Hashing Source: https://github.com/chrizog/someipy/blob/master/docs/api/method.md Provides methods for checking equality between Method objects and for hashing them. ```APIDOC ## __eq__(__Method__value) ### Description Check equality with another Method based on id and protocol. ### Parameters __value : Another Method instance. ### Returns bool : True if ids and protocols match, False otherwise. * **Parameters:** **__Method__value** (*object*) * **Return type:** bool ## __hash__() ### Description Hashes object. ### Returns int : Hash of object * **Return type:** int ``` -------------------------------- ### Subscribe to SOME/IP Events Source: https://context7.com/chrizog/someipy/llms.txt This client code subscribes to a SOME/IP event group and registers a callback to handle incoming events. Ensure the service and event definitions match the server's configuration. The subscription has a Time-To-Live (TTL) in seconds. ```python from dataclasses import dataclass from someipy.serialization import SomeIpPayload, SomeIpFixedSizeArray, Uint64, Float32 @dataclass class TemperatureMsg(SomeIpPayload): timestamp: Uint64 measurements: SomeIpFixedSizeArray def __init__(self): self.timestamp = Uint64() self.measurements = SomeIpFixedSizeArray(Float32, 4) SAMPLE_SERVICE_ID = 0x1234 SAMPLE_INSTANCE_ID = 0x5678 SAMPLE_EVENTGROUP_ID = 0x0321 SAMPLE_EVENT_ID = 0x0123 def temperature_callback(event_id: int, event_payload: bytes) -> None: """Callback invoked when an event is received.""" try: print(f"Received {len(event_payload)} bytes for event 0x{event_id:04x}") temperature_msg = TemperatureMsg().deserialize(event_payload) print(f"Timestamp: {temperature_msg.timestamp.value}") print(f"Measurements: {[m.value for m in temperature_msg.measurements.data]}") except Exception as e: print(f"Error in deserialization: {e}") async def main(): set_someipy_log_level(logging.DEBUG) someipy_daemon = await connect_to_someipy_daemon() # Define the service (must match server's service definition) temperature_event = Event(id=SAMPLE_EVENT_ID, protocol=TransportLayerProtocol.UDP) temperature_eventgroup = EventGroup(id=SAMPLE_EVENTGROUP_ID, events=[temperature_event]) temperature_service = ( ServiceBuilder() .with_service_id(SAMPLE_SERVICE_ID) .with_major_version(1) .with_eventgroup(temperature_eventgroup) .build() ) # Create client service instance client_instance = ClientServiceInstance( daemon=someipy_daemon, service=temperature_service, instance_id=SAMPLE_INSTANCE_ID, endpoint_ip="127.0.0.1", endpoint_port=3002, ) # Register callback for received events client_instance.register_callback(temperature_callback) # Subscribe to the event group (TTL in seconds) client_instance.subscribe_eventgroup(temperature_eventgroup, 5) try: # Keep running to receive events await asyncio.Future() except asyncio.CancelledError: print("Shutting down...") client_instance.unsubscribe_eventgroup(temperature_eventgroup) finally: await someipy_daemon.disconnect_from_daemon() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Configure someipy Logging Level Source: https://github.com/chrizog/someipy/blob/master/docs/getting_started.md Set the logging level for the someipy library. Choose from standard Python logging levels. ```python import logging async def main(): # .. our application will go here set_someipy_log_level(logging.DEBUG) ``` -------------------------------- ### ClientServiceInstance Methods Source: https://github.com/chrizog/someipy/blob/master/docs/api/client_service_instance.md Provides methods for calling SOME/IP methods, subscribing to events, and managing service instance availability. ```APIDOC ## ClientServiceInstance Methods ### call_method #### Description Asynchronously calls a SOME/IP method on the service instance. #### Parameters - **method_id** (int) - The identifier of the method to call. - **payload** (bytes) - The payload data for the method call. #### Return type: MethodResult ### is_available #### Description Asynchronously checks if the service instance is available. #### Return type: bool ### register_callback #### Description Registers a callback function to be invoked when a SOME/IP event is received. #### Parameters - **callback** (Callable[[int, bytes], None]) - The callback function to register. It accepts event_id (int) and payload (bytes). #### Return type: None ### subscribe_eventgroup #### Description Subscribes to a specific SOME/IP event group. #### Parameters - **eventgroup** (EventGroup) - The event group to subscribe to. - **ttl_subscription_seconds** (int) - The time-to-live for the subscription in seconds. ### unsubscribe_eventgroup #### Description Unsubscribes from a SOME/IP event group. #### Parameters - **eventgroup** (EventGroup) - The event group to unsubscribe from. ``` -------------------------------- ### Prepare and Send SOME/IP Events Source: https://github.com/chrizog/someipy/blob/master/docs/getting_started.md Prepare message data using defined types and serialize it before sending. Events are sent cyclically using the send_event method on the service instance, requiring the event group ID, event ID, and serialized payload. ```python from someipy.serialization import Uint8, Uint64, Float32 from temperature_msg import TemperatureMsg async def main(): # ... tmp_msg = TemperatureMsg() tmp_msg.version.major = Uint8(1) tmp_msg.version.minor = Uint8(0) tmp_msg.measurements.data[0] = Float32(20.0) tmp_msg.measurements.data[1] = Float32(21.0) tmp_msg.measurements.data[2] = Float32(22.0) tmp_msg.measurements.data[3] = Float32(23.0) # ... try: # Cyclically send events in an endless loop... while True: await asyncio.sleep(1) tmp_msg.timestamp = Uint64(tmp_msg.timestamp.value + 1) payload = tmp_msg.serialize() service_instance_temperature.send_event( SAMPLE_EVENTGROUP_ID, SAMPLE_EVENT_ID, payload ) except asyncio.CancelledError: print("Stop offering service...") await service_instance_temperature.stop_offer() finally: print("Service Discovery close...") service_discovery.close() # ... ``` -------------------------------- ### SOME/IP SD Daemon Configuration Source: https://github.com/chrizog/someipy/blob/master/docs/service_discovery.md JSON configuration for the someipy daemon's Service Discovery. Specifies the multicast address, port, and network interface for SD messages. ```json { "sd_address": "224.224.224.245", "sd_port": 30490, "interface": "127.0.0.1" } ``` -------------------------------- ### Define a SOME/IP Service Source: https://github.com/chrizog/someipy/blob/master/docs/whatsnew.md Defines a SOME/IP service, including its ID, major version, and associated methods. This is a prerequisite for building client or server instances. ```python addition_method = Method( id=SAMPLE_METHOD_ID, protocol=TransportLayerProtocol.UDP, ) addition_service = ( ServiceBuilder() .with_service_id(SAMPLE_SERVICE_ID) .with_major_version(1) .with_method(addition_method) .build() ``` -------------------------------- ### Call Method and Deserialize Result Source: https://github.com/chrizog/someipy/blob/master/docs/whatsnew.md Prepares method parameters, calls a SOME/IP method on a service instance, and deserializes the response payload. Ensure the parameter and result types match the service definition. ```python method_parameter = Addends(addend1=1, addend2=2) method_result = await client_instance_addition.call_method( SAMPLE_METHOD_ID, method_parameter.serialize() ) sum = Sum().deserialize(method_result.payload) print(f"Sum: {sum.value.value}") ``` -------------------------------- ### Define a SOME/IP Service with a Method Source: https://github.com/chrizog/someipy/blob/master/docs/offering_methods.md This code defines a SOME/IP service and adds a method to it using the ServiceBuilder. The Method object holds the method ID and handler, while the Service object aggregates methods for a specific service ID. ```python SAMPLE_SERVICE_ID = 0x1234 addition_method = Method( id=SAMPLE_METHOD_ID, protocol=TransportLayerProtocol.UDP, method_handler=add_method_handler, ) addition_service = ( ServiceBuilder() .with_service_id(SAMPLE_SERVICE_ID) .with_major_version(1) .with_method(addition_method) .build() ) ``` -------------------------------- ### SomeIPy Classes Source: https://github.com/chrizog/someipy/blob/master/docs/api/index.md Documentation for the core classes within the SomeIPy library. ```APIDOC ## SomeIPy Classes This section details the available classes in the SomeIPy library. ### Classes * **Service**: Represents a service in the SomeIPy framework. * **ServiceBuilder**: A builder class for constructing Service objects. * **Method**: Represents a method that can be called or exposed. * **MethodResult**: Represents the result of a method call. * **EventGroup**: Manages a group of events. * **Event**: Represents an event that can be sent or received. * **ServerServiceInstance**: Manages a service instance on the server side. * **ClientServiceInstance**: Manages a service instance on the client side. * **Serialization**: Handles data serialization and deserialization. * **TransportLayerProtocol**: Defines the transport layer protocol used. * **MessageType**: Defines the types of messages exchanged. * **ReturnCode**: Represents the return codes for operations. ``` -------------------------------- ### SomeIPy Functions Source: https://github.com/chrizog/someipy/blob/master/docs/api/index.md Documentation for the utility functions provided by the SomeIPy library. ```APIDOC ## SomeIPy Functions This section details the utility functions available in the SomeIPy library. ### Functions * **connect_to_someipy_daemon**: Establishes a connection to the SomeIPy daemon. * **someipy_logging**: Configures logging for the SomeIPy library. ``` -------------------------------- ### Define SOME/IP Service with Eventgroup Source: https://github.com/chrizog/someipy/blob/master/docs/subscribing_events.md Defines a SOME/IP service, including an eventgroup and a specific event. Uses ServiceBuilder for convenience. Ensure correct service ID, major version, and eventgroup ID are specified. ```python from someipy import ServiceBuilder, EventGroup, Event, TransportLayerProtocol SAMPLE_SERVICE_ID = 0x1234 SAMPLE_INSTANCE_ID = 0x5678 SAMPLE_EVENTGROUP_ID = 0x0321 SAMPLE_EVENT_ID = 0x0123 temperature_event = Event(id=SAMPLE_EVENT_ID, protocol=TransportLayerProtocol.UDP) temperature_eventgroup = EventGroup( id=SAMPLE_EVENTGROUP_ID, events=[temperature_event] ) temperature_service = ( ServiceBuilder() .with_service_id(SAMPLE_SERVICE_ID) .with_major_version(1) .with_eventgroup(temperature_eventgroup) .build() ) ``` -------------------------------- ### Shutdown Application Source: https://github.com/chrizog/someipy/blob/master/docs/offering_events.md Ensure a clean shutdown by stopping the service offer and disconnecting from the someipy daemon. This is crucial for releasing resources and terminating connections properly. ```python await service_instance_temperature.stop_offer() await someipy_daemon.disconnect_from_daemon() ``` -------------------------------- ### Call SOME/IP Method (Client) Source: https://context7.com/chrizog/someipy/llms.txt Demonstrates how to call a remote SOME/IP method from a client. The `call_method` function is asynchronous and returns a `MethodResult` object containing the response from the server. ```python import asyncio import logging from dataclasses import dataclass from someipy import ( ClientServiceInstance, ServiceBuilder, Method, MessageType, ReturnCode, TransportLayerProtocol, connect_to_someipy_daemon, ) from someipy.someipy_logging import set_someipy_log_level from someipy.serialization import SomeIpPayload, Sint16, Sint32 # Assume Addends, Sum, Sint16, Sint32, SomeIpPayload are defined elsewhere # Example usage (assuming a server is running and discoverable): # async def call_add_method(): # set_someipy_log_level(logging.DEBUG) # someipy_daemon = await connect_to_someipy_daemon() # client_instance = ClientServiceInstance( # daemon=someipy_daemon, # service_id=SAMPLE_SERVICE_ID, # Use the same service ID as the server # instance_id=SAMPLE_INSTANCE_ID, # Use the same instance ID as the server # major_version=1 # ) # # addends_payload = Addends(addend1=5, addend2=7) # method_result = await client_instance.call_method( # method_id=SAMPLE_METHOD_ID, # Use the same method ID as the server # payload=addends_payload.serialize() # ) # # if method_result.return_code == ReturnCode.E_OK: # response_sum = Sum() # response_sum.deserialize(method_result.payload) # print(f"Result: {response_sum.value.value}") # else: # print(f"Error calling method: {method_result.return_code}") # # await someipy_daemon.disconnect_from_daemon() # # if __name__ == "__main__": # asyncio.run(call_add_method()) ``` -------------------------------- ### Configure SOME/IP Logging Level Source: https://context7.com/chrizog/someipy/llms.txt Set the logging verbosity for the someipy library. Use this to control the amount of debug information printed during operation. ```python import logging from someipy.someipy_logging import set_someipy_log_level # Available log levels (from most to least verbose) set_someipy_log_level(logging.DEBUG) # Detailed debug information set_someipy_log_level(logging.INFO) # General operational messages set_someipy_log_level(logging.WARNING) # Warning messages only set_someipy_log_level(logging.ERROR) # Error messages only ```