Skip to content

Commit

Permalink
Adapt tests for seat adjuster to work after importing to template (#88)
Browse files Browse the repository at this point in the history
* Adapt tests for seat adjuster to work after importing to template
* Update pre commit hook versions
* Align linter with template
* Add adaptions for correct unit testing
---------

Signed-off-by: Dennis Meister <[email protected]>
  • Loading branch information
dennismeister93 authored Jul 7, 2023
1 parent 466299b commit f32b017
Show file tree
Hide file tree
Showing 15 changed files with 403 additions and 222 deletions.
34 changes: 34 additions & 0 deletions .github/actions/pre-commit-action/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Copyright (c) 2022-2023 Robert Bosch GmbH and Microsoft Corporation
#
# This program and the accompanying materials are made available under the
# terms of the Apache License, Version 2.0 which is available at
# https://www.apache.org/licenses/LICENSE-2.0.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# SPDX-License-Identifier: Apache-2.0

name: pre-commit
description: run pre-commit
inputs:
extra_args:
description: Options to pass to pre-commit run
required: false
default: "--all-files"
runs:
using: composite
steps:
- run: python -m pip install pre-commit
shell: bash
- run: python -m pip freeze --local
shell: bash
- uses: actions/cache@v3
with:
path: ~/.cache/pre-commit
key: pre-commit-3|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }}
- run: pre-commit run --show-diff-on-failure --color=always ${{ inputs.extra_args }}
shell: bash
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ jobs:
python3 -m pip install tox-gh-actions
- name: Run Linters
uses: pre-commit/action@v3.0.0
uses: ./.github/actions/pre-commit-action

- name: Run the daparized databroker binary
run: |
Expand Down
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ repos:
)$
- repo: https://github.com/psf/black
rev: 22.10.0
rev: 23.1.0
hooks:
- id: black
exclude: >
Expand Down Expand Up @@ -103,7 +103,7 @@ repos:
pass_filenames: false

- repo: https://github.com/pycqa/pydocstyle
rev: 6.1.1
rev: 6.3.0
hooks:
- id: pydocstyle
exclude: >
Expand Down
1 change: 0 additions & 1 deletion NOTICE-3RD-PARTY-CONTENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,5 +100,4 @@
|actions/setup-python|v4|MIT License|
|actions/upload-artifact|v3|MIT License|
|github/codeql-action|v2|MIT License|
|pre-commit/action|v3.0.0|MIT License|
|softprops/action-gh-release|v1|MIT License|
1 change: 0 additions & 1 deletion examples/dog-mode/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ async def on_change(self, data: DataPointReply):
)

async def display_values(self):

logger.info("Publish Current Temperature and StateOfCharge")
try:
logger.info(
Expand Down
2 changes: 1 addition & 1 deletion examples/seat-adjuster/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ RUN pip3 install --no-cache-dir pyinstaller==5.9.0 \

WORKDIR /app

RUN pyinstaller --clean -F -s src/main.py
RUN pyinstaller --clean -F -s --paths=src src/main.py

WORKDIR /app/dist

Expand Down
2 changes: 1 addition & 1 deletion examples/seat-adjuster/requirements-links.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
git+https://github.com/eclipse-velocitas/[email protected].1
git+https://github.com/eclipse-velocitas/[email protected].2
76 changes: 3 additions & 73 deletions examples/seat-adjuster/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,97 +12,27 @@
#
# SPDX-License-Identifier: Apache-2.0

"""A sample Velocitas vehicle app for adjusting seat position."""
"""The launcher for starting a Vehicle App."""

import asyncio
import json
import logging
import signal

from vehicle import Vehicle, vehicle # type: ignore
from vapp import SeatAdjusterApp # type: ignore # noqa: E402
from vehicle import vehicle # type: ignore

from sdv.util.log import ( # type: ignore
get_opentelemetry_log_factory,
get_opentelemetry_log_format,
)
from sdv.vdb.subscriptions import DataPointReply
from sdv.vehicle_app import VehicleApp, subscribe_topic

logging.setLogRecordFactory(get_opentelemetry_log_factory())
logging.basicConfig(format=get_opentelemetry_log_format())
logging.getLogger().setLevel("DEBUG")
logger = logging.getLogger(__name__)


class SeatAdjusterApp(VehicleApp):
"""
Sample Velocitas Vehicle App.
The SeatAdjusterApp subscribes to a MQTT topic to listen for incoming
requests to change the seat position and calls the SeatService to move the seat
upon such a request, but only if Vehicle.Speed equals 0.
It also subcribes to the VehicleDataBroker for updates of the
Vehicle.Cabin.Seat.Row1.Pos1.Position signal and publishes this
information via another specific MQTT topic
"""

def __init__(self, vehicle_client: Vehicle):
super().__init__()
self.Vehicle = vehicle_client

async def on_start(self):
"""Run when the vehicle app starts"""
await self.Vehicle.Cabin.Seat.Row1.Pos1.Position.subscribe(
self.on_seat_position_changed
)

async def on_seat_position_changed(self, data: DataPointReply):
response_topic = "seatadjuster/currentPosition"
await self.publish_event(
response_topic,
json.dumps(
{"position": data.get(self.Vehicle.Cabin.Seat.Row1.Pos1.Position).value}
),
)

@subscribe_topic("seatadjuster/setPosition/request")
async def on_set_position_request_received(self, data_str: str) -> None:
data = json.loads(data_str)
response_topic = "seatadjuster/setPosition/response"
response_data = {"requestId": data["requestId"], "result": {}}

vehicle_speed = (await self.Vehicle.Speed.get()).value

position = data["position"]
if vehicle_speed == 0:
try:
await self.Vehicle.Cabin.Seat.Row1.Pos1.Position.set(position)
response_data["result"] = {
"status": 0,
"message": f"Set Seat position to: {position}",
}
except ValueError as error:
response_data["result"] = {
"status": 1,
"message": f"Failed to set the position {position}, error: {error}",
}
except Exception:
response_data["result"] = {
"status": 1,
"message": "Exception on set Seat position",
}

else:
error_msg = f"""Not allowed to move seat because vehicle speed
is {vehicle_speed} and not 0"""
response_data["result"] = {"status": 1, "message": error_msg}

await self.publish_event(response_topic, json.dumps(response_data))


async def main():

"""Main function"""
logger.info("Starting seat adjuster app...")
seat_adjuster_app = SeatAdjusterApp(vehicle)
Expand Down
99 changes: 99 additions & 0 deletions examples/seat-adjuster/src/vapp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Copyright (c) 2022-2023 Robert Bosch GmbH and Microsoft Corporation
#
# This program and the accompanying materials are made available under the
# terms of the Apache License, Version 2.0 which is available at
# https://www.apache.org/licenses/LICENSE-2.0.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# SPDX-License-Identifier: Apache-2.0

"""A sample Velocitas vehicle app for adjusting seat position."""

import json
import logging

from vehicle import Vehicle # type: ignore

from sdv.util.log import ( # type: ignore
get_opentelemetry_log_factory,
get_opentelemetry_log_format,
)
from sdv.vdb.reply import DataPointReply
from sdv.vehicle_app import VehicleApp, subscribe_topic

logging.setLogRecordFactory(get_opentelemetry_log_factory())
logging.basicConfig(format=get_opentelemetry_log_format())
logging.getLogger().setLevel("DEBUG")
logger = logging.getLogger(__name__)


class SeatAdjusterApp(VehicleApp):
"""
Sample Velocitas Vehicle App.
The SeatAdjusterApp subscribes to a MQTT topic to listen for incoming
requests to change the seat position and calls the SeatService to move the seat
upon such a request, but only if Vehicle.Speed equals 0.
It also subcribes to the VehicleDataBroker for updates of the
Vehicle.Cabin.Seat.Row1.Pos1.Position signal and publishes this
information via another specific MQTT topic
"""

def __init__(self, vehicle_client: Vehicle):
super().__init__()
self.Vehicle = vehicle_client

async def on_start(self):
"""Run when the vehicle app starts"""
await self.Vehicle.Cabin.Seat.Row1.Pos1.Position.subscribe(
self.on_seat_position_changed
)

async def on_seat_position_changed(self, data: DataPointReply):
response_topic = "seatadjuster/currentPosition"
await self.publish_event(
response_topic,
json.dumps(
{"position": data.get(self.Vehicle.Cabin.Seat.Row1.Pos1.Position).value}
),
)

@subscribe_topic("seatadjuster/setPosition/request")
async def on_set_position_request_received(self, data_str: str) -> None:
data = json.loads(data_str)
response_topic = "seatadjuster/setPosition/response"
response_data = {"requestId": data["requestId"], "result": {}}

vehicle_speed = (await self.Vehicle.Speed.get()).value

position = data["position"]
if vehicle_speed == 0:
try:
await self.Vehicle.Cabin.Seat.Row1.Pos1.Position.set(position)
response_data["result"] = {
"status": 0,
"message": f"Set Seat position to: {position}",
}
except ValueError as error:
response_data["result"] = {
"status": 1,
"message": f"Failed to set the position {position}, error: {error}",
}
except Exception:
response_data["result"] = {
"status": 1,
"message": "Exception on set Seat position",
}

else:
error_msg = f"""Not allowed to move seat because vehicle speed
is {vehicle_speed} and not 0"""
response_data["result"] = {"status": 1, "message": error_msg}

await self.publish_event(response_topic, json.dumps(response_data))
Loading

0 comments on commit f32b017

Please sign in to comment.