Skip to content

Commit

Permalink
workshop end
Browse files Browse the repository at this point in the history
  • Loading branch information
kianwasabi committed Nov 7, 2023
1 parent 9b55769 commit 53db17f
Showing 1 changed file with 88 additions and 8 deletions.
96 changes: 88 additions & 8 deletions app/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@
import asyncio
import json
import logging
from logging.handlers import TimedRotatingFileHandler
import signal
import random
# from flask import Flask, request, send_file
# from flask_cors import CORS
import os


from vehicle import Vehicle, vehicle # type: ignore
from velocitas_sdk.util.log import ( # type: ignore
Expand All @@ -32,11 +38,38 @@
logging.basicConfig(format=get_opentelemetry_log_format())
logging.getLogger().setLevel("DEBUG")
logger = logging.getLogger(__name__)

GET_SPEED_REQUEST_TOPIC = "sampleapp/getSpeed"
GET_SPEED_RESPONSE_TOPIC = "sampleapp/getSpeed/response"
DATABROKER_SUBSCRIPTION_TOPIC = "sampleapp/currentSpeed"

DATABROKER_SUBSCRIPTION_TOPIC_SPEED = "sampleapp/currentSpeed"
# GET_CRASHED_REQUEST_TOPIC = "sampleapp/getCrashed"
# GET_CRASHED_RESPONSE_TOPIC = "sampleapp/getCrashed/response"
DATABROKER_SUBSCRIPTION_TOPIC_CRASHED = "sampleapp/crashed"

# Configure the crash diagnostic logger (shoutout @Lagavulin9)
SPEED_LOG_PATH = "logs/vehicle/crash_diagnostic/"
SPEED_LOGGER_NAME = "speed"
SPEED_LOG_FORMAT = "%(asctime)s [%(name)s] - %(message)s"
os.makedirs(os.path.dirname(SPEED_LOG_PATH), exist_ok=True)
for file in os.listdir(SPEED_LOG_PATH):
os.remove(SPEED_LOG_PATH + file)
speedLogHandler = TimedRotatingFileHandler(
filename=SPEED_LOG_PATH+SPEED_LOGGER_NAME+".log",
when="s",
interval=10,
backupCount=5,
encoding="UTF-8")
speedLogHandler.setFormatter(logging.Formatter(SPEED_LOG_FORMAT))
speedLogHandler.suffix = '%H-%M-%S'
speedLogHandler.extMatch
loggerCrashDiagnosticSpeed = logging.getLogger(SPEED_LOGGER_NAME)
loggerCrashDiagnosticSpeed.addHandler(speedLogHandler)
loggerCrashDiagnosticSpeed.setLevel("INFO")

# Flask server for crash diagnostic report
# Flask_app = Flask(__name__)
# CORS(Flask_app, resources={r"/*": {"origins": "*"}})
# DOMAIN = "https://localhost:4000"
# ENDPOINT = "api/crash_diagnostic_report"

class SampleApp(VehicleApp):
"""
Expand All @@ -58,12 +91,24 @@ def __init__(self, vehicle_client: Vehicle):
super().__init__()
self.Vehicle = vehicle_client

async def random_vehicle_crash(self):
crashed = random.random() < 0.01
if (crashed):
return True
return False

# @Flask_app.route(ENDPOINT, methods=['GET'])
# async def send_crash_diagnostic_report(self):
# res_data = {"crashed ": }
# response = make_response(jsonify(res_data))

async def on_start(self):
"""Run when the vehicle app starts"""
# This method will be called by the SDK when the connection to the
# Vehicle DataBroker is ready.
# Here you can subscribe for the Vehicle Signals update (e.g. Vehicle Speed).
await self.Vehicle.Speed.subscribe(self.on_speed_change)
await self.Vehicle.Speed.subscribe(self.on_crashed_change)

async def on_speed_change(self, data: DataPointReply):
"""The on_speed_change callback, this will be executed when receiving a new
Expand All @@ -73,14 +118,24 @@ async def on_speed_change(self, data: DataPointReply):
# the same callback.
vehicle_speed = data.get(self.Vehicle.Speed).value

# Do anything with the received value.
# Example:
# - Publishes current speed to MQTT Topic (i.e. DATABROKER_SUBSCRIPTION_TOPIC).
# save received value to logger
loggerCrashDiagnosticSpeed.info("vehicle_speed %s", vehicle_speed)

# - Publishes current speed to MQTT Topic
# (i.e. DATABROKER_SUBSCRIPTION_TOPIC_SPEED).
await self.publish_event(
DATABROKER_SUBSCRIPTION_TOPIC,
DATABROKER_SUBSCRIPTION_TOPIC_SPEED,
json.dumps({"speed": vehicle_speed}),
)

async def on_crashed_change(self, data: DataPointReply):
vehicle_crashed = await self.random_vehicle_crash()
if vehicle_crashed:
await self.publish_event(
DATABROKER_SUBSCRIPTION_TOPIC_CRASHED,
json.dumps({"crashed ": vehicle_crashed}),
)

@subscribe_topic(GET_SPEED_REQUEST_TOPIC)
async def on_get_speed_request_received(self, data: str) -> None:
"""The subscribe_topic annotation is used to subscribe for incoming
Expand All @@ -96,7 +151,6 @@ async def on_get_speed_request_received(self, data: str) -> None:

# Getting current speed from VehicleDataBroker using the DataPoint getter.
vehicle_speed = (await self.Vehicle.Speed.get()).value

# Do anything with the speed value.
# Example:
# - Publishes the vehicle speed to MQTT topic (i.e. GET_SPEED_RESPONSE_TOPIC).
Expand All @@ -112,13 +166,39 @@ async def on_get_speed_request_received(self, data: str) -> None:
),
)

# @subscribe_topic(GET_CRASHED_REQUEST_TOPIC)
# async def on_get_crashed_request_received(self, data: str) -> None:
# # Use the logger with the preferred log level (e.g. debug, info, error, etc)
# logger.debug(
# "PubSub event for the Topic: %s -> is received with the data: %s",
# GET_SPEED_REQUEST_TOPIC,
# data,
# )

# random_vehicle_crash = await self.random_vehicle_crash()

# # Publishes to MQTT topic
# await self.publish_event(
# GET_CRASHED_RESPONSE_TOPIC,
# json.dumps(
# {
# "result": {
# "status": 0,
# "message": f"""Current Speed = {random_vehicle_crash}""",
# },
# }
# ),
# )



async def main():
"""Main function"""
logger.info("Starting SampleApp...")
# Constructing SampleApp and running it.
vehicle_app = SampleApp(vehicle)
await vehicle_app.run()
await app.run()


LOOP = asyncio.get_event_loop()
Expand Down

0 comments on commit 53db17f

Please sign in to comment.