const axios = require('axios');
// Linking our mongodb launches collection
const launchesDatabase = require('./launches.mongo');
const planets = require('./planets.mongo');
// Default flight number in case our getLatestLaunch function has no launches to reference
const DEFAULT_FLIGHT_NUMBER = 100;
// SpaceX API url
const SPACEX_API_URL = "https://api.spacexdata.com/v4/launches/query";
// Saving SpaceX launches to our database
async function populateLaunches() {
console.log("Downloading launches data...");
const response = await axios.post(SPACEX_API_URL, {
query: {},
options: {
pagination: false,
populate: [
{
path: 'rocket',
select: {
name: 1
}
},
{
path: 'payloads',
select: {
'customers': 1
}
}
]
}
});
if (response.status != 200) {
console.log('Problem downloading launch data');
throw new Error('Launch data download failed');
}
// Response from our axios query for launch data, which axios stores in a docs array in the response.data
const launchDocs = response.data.docs
// Looping over the launch data to make a launch object to save in our database
for (const launchDoc of launchDocs) {
// Using the built in flatMap() function to make a new array out of each element in the array where customers are stored, it is called on an array and takes a callback which runs on each element and then combines the results of each into a new array
const payloads = launchDoc['payloads'];
// Iterating over each payload and taking each customers value for each payload and combining them into an array to use in our new launch document, creating the new document, and saving it to mongodb
const customers = payloads.flatMap((payload) => {
return payload['customers'];
});
const launch = {
flightNumber: launchDoc['flight_number'],
mission: launchDoc['name'],
rocket: launchDoc['rocket']['name'],
launchDate: launchDoc['date_local'],
upcoming: launchDoc['upcoming'],
success: launchDoc['success'],
customers
}
console.log(`${launch.flightNumber}, ${launch.mission}`);
// Populate launches collection
await saveLaunch(launch);
}
}
// Loading all the SpaceX launch data we need with axios
async function loadLaunchesData() {
// Checking if the data has already been loaded
const firstLaunch = await findLaunch({
flightNumber: 1,
rocket: 'Falcon 1',
mission: 'FalconSat'
});
if (firstLaunch) {
console.log('Launch data already loaded');
} else {
await populateLaunches();
}
}
// Function to use to only add launches not in our database already
async function findLaunch(filter) {
return await launchesDatabase.findOne(filter);
}
// See if a launch exists within our database
async function existsLaunchWithId(launchId) {
return await findLaunch({
flightNumber: launchId
});
}
// Get our latest flight number from the database using a filter that finds the highest flight number value
async function getLatestFlightNumber() {
const latestLaunch = await launchesDatabase
.findOne()
.sort('-flightNumber');
if (!latestLaunch) {
return DEFAULT_FLIGHT_NUMBER;
}
return latestLaunch.flightNumber;
}
// GET all launches
async function getAllLaunches(skip, limit) {
return await launchesDatabase
.find({}, { '_id': 0, '__v': 0})
.sort({ flightNumber: 1 })
.skip(skip)
.limit(limit);
}
// Saving launches to mongodb
async function saveLaunch(launch) {
// Saving a doocument with the newly passed in launch object, or updating it if it already exists by flight number
try {
await launchesDatabase.findOneAndUpdate({
flightNumber: launch.flightNumber,
}, launch, {
upsert: true
})} catch(err) {
return console.error(`Could not save launch ${err}`);
}
}
// Adding a document containing a new launch to mongodb
async function scheduleNewLaunch(launch) {
// Validating the planet exists, so we do not add launches to planets that do not exist in our database
const planet = await planets.findOne({
keplerName: launch.target
});
if (!planet) {
throw new Error('No matching planet was found');
}
const newFlightNumber = await getLatestFlightNumber() + 1;
const newLaunch = Object.assign(launch, {
success: true,
upcoming: true,
customers: ['ZTM', 'NASA'],
flightNumber: newFlightNumber
});
await saveLaunch(newLaunch);
}
// Rather than deleting aborted launches outright, update them to show they are not successful and are no longer upcoming
async function abortLaunchById(launchId) {
const aborted = await launchesDatabase.updateOne({
flightNumber: launchId
}, {
upcoming: false,
success: false
});
/* Returning that a document was modified, and that one document was modified. We can see this object by reading the res.json from our controller function if we simply used the above await updateOne operation, like below
const aborted = await abortLaunchById(launchId);
return res.status(200).json(aborted); */
return aborted.modifiedCount === 1;
}
module.exports = {
loadLaunchesData,
existsLaunchWithId,
getAllLaunches,
scheduleNewLaunch,
abortLaunchById
};
const { RESTDataSource } = require('apollo-datasource-rest');
class LaunchAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://api.spacexdata.com/v2/';
}
// Create a rocket object although it is based on a launch
rocketReducer(launch) {
let launchFailureDetails = null
if(launch.launch_failure_details) {
launchFailureDetails = launch.launch_failure_details.reason
}
return {
id: launch.rocket.rocket_id,
name: launch.rocket.rocket_name,
mission: {
name: launch.mission_name,
launchDateLocal: launch.launch_date_local,
launchSuccess: launch.launch_success,
launchFailureDetails: launchFailureDetails,
missionPatchSmall:launch.links.mission_patch_small
},
site: {
name: launch.launch_site.site_name
}
}
};
// Group launches by rocket id
groupRockets(launches) {
const launchesByRocket = new Map();
let rocketId, rocketLaunches;
launches.forEach((launch) => {
rocketId = launch.rocket.rocket_id;
rocketLaunches = launchesByRocket.get(rocketId);
if (!rocketLaunches) {
launchesByRocket.set(rocketId, launch);
} else {
// To simplify the project, I'll use only one launch per rocket
// rocketLaunches.push(launch)
}
})
return launchesByRocket;
}
// leaving this inside the class to make the class easier to test
launchReducer(launch) {
return {
id: launch.flight_number || 0,
cursor: `${launch.launch_date_local}`,
site: launch.launch_site && launch.launch_site.site_name,
mission: {
name: launch.mission_name,
missionPatchSmall: launch.links.mission_patch_small,
missionPatchLarge: launch.links.mission_patch,
},
rocket: {
id: launch.rocket.rocket_id,
name: launch.rocket.rocket_name,
type: launch.rocket.rocket_type,
},
};
}
async getAllRockets() {
const response = await this.get('launches');
if (Array.isArray(response)) {
const launchesPerRocket = Array.from(this.groupRockets(response).values());
const result = launchesPerRocket.map(launch => this.rocketReducer(launch))
return result
} else {
return []
}
}
async getAllLaunches() {
const response = await this.get('launches');
// transform the raw launches to a more friendly
return Array.isArray(response)
? response.map(launch => this.launchReducer(launch)) : [];
}
async getLaunchById({ launchId }) {
const res = await this.get('launches', { flight_number: launchId });
return this.launchReducer(res[0]);
}
async getLaunchesByIds({ launchIds }) {
return Promise.all(
launchIds.map(launchId => this.getLaunchById({ launchId })),
);
}
}
module.exports = LaunchAPI;
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright 2018 ROBOTIS CO., LTD.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://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.
################################################################################
# Authors: Leon Jung, [AuTURBO] Kihoon Kim (https://github.com/auturbo), Gilbert
import rospy, roslaunch
import numpy as np
import subprocess
import os
import sys
from enum import Enum
from std_msgs.msg import UInt8
class CoreNodeController():
def __init__(self):
self.ros_package_path = os.path.dirname(os.path.realpath(__file__))
self.ros_package_path = self.ros_package_path.replace('turtlebot3_autorace_core/nodes', '')
self.sub_mode_control = rospy.Subscriber('/core/decided_mode', UInt8, self.cbReceiveMode, queue_size=1)
self.CurrentMode = Enum('CurrentMode', 'idle lane_following traffic_light parking_lot level_crossing tunnel')
# subscribes : status returned
self.sub_parking_lot_stamped = rospy.Subscriber('/detect/parking_lot_stamped', UInt8, self.cbParkingLotStamped, queue_size=1)
self.sub_level_crossing_stamped = rospy.Subscriber('/detect/level_crossing_stamped', UInt8, self.cbLevelCrossingStamped, queue_size=1)
self.sub_tunnel_stamped = rospy.Subscriber('/detect/tunnel_stamped', UInt8, self.cbTunnelStamped, queue_size=1)
# publishes orders
self.pub_traffic_light_order = rospy.Publisher('/detect/traffic_light_order', UInt8, queue_size=1)
self.pub_parking_lot_order = rospy.Publisher('/detect/parking_lot_order', UInt8, queue_size=1)
self.pub_level_crossing_order = rospy.Publisher('/detect/level_crossing_order', UInt8, queue_size=1)
self.pub_tunnel_order = rospy.Publisher('/detect/tunnel_order', UInt8, queue_size=1)
self.pub_mode_return = rospy.Publisher('/core/returned_mode', UInt8, queue_size=1)
self.StepOfParkingLot = Enum('StepOfParkingLot', 'searching_parking_sign searching_parking_point_line searching_nonreserved_parking_area parking')
self.StepOfLevelCrossing = Enum('StepOfLevelCrossing', 'searching_stop_sign searching_level watching_level stop pass_level')
self.StepOfTunnel = Enum('StepOfTunnel', 'searching_tunnel_sign go_in_to_tunnel navigation go_out_from_tunnel exit')
self.current_step_parking_lot = self.StepOfParkingLot.searching_parking_sign.value
self.current_step_level_crossing = self.StepOfLevelCrossing.searching_stop_sign.value
self.current_step_tunnel = self.StepOfTunnel.searching_tunnel_sign.value
self.Launcher = Enum('Launcher', 'launch_camera_ex_calib launch_detect_sign launch_detect_lane launch_control_lane launch_detect_traffic_light launch_control_traffic_light launch_detect_parking launch_control_parking launch_detect_level launch_control_level launch_detect_tunnel launch_control_tunnel')
self.uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)
self.launch_camera_launched = False
self.launch_detect_sign_launched = False
self.launch_detect_lane_launched = False
self.launch_control_lane_launched = False
self.launch_detect_parking_launched = False
self.launch_control_parking_launched = False
self.launch_detect_level_launched = False
self.launch_detect_traffic_light_launched = False
self.launch_detect_tunnel_launched = False
self.launch_control_tunnel_launched = False
self.current_mode = self.CurrentMode.idle.value
self.is_triggered = False
loop_rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
if self.is_triggered == True:
self.fnControlNode()
loop_rate.sleep()
def cbReceiveMode(self, mode_msg):
rospy.loginfo("starts the progress with %d", mode_msg.data)
self.current_mode = mode_msg.data
self.is_triggered = True
# Which step is in Parking Lot
def cbParkingLotStamped(self, parking_lot_msg):
rospy.loginfo("ParkingLot Step changed from %d", self.current_step_parking_lot)
self.current_step_parking_lot = parking_lot_msg.data
rospy.loginfo("into %d", self.current_step_parking_lot)
if self.current_step_parking_lot == self.StepOfParkingLot.parking.value:
self.current_mode = self.CurrentMode.lane_following.value
msg_mode_return = UInt8()
msg_mode_return.data = self.current_mode
self.current_step_parking_lot = self.StepOfParkingLot.searching_parking_sign.value
rospy.loginfo("pub_mode_return")
self.pub_mode_return.publish(msg_mode_return)
self.is_triggered = True
# Which step is in Level Crossing
def cbLevelCrossingStamped(self, level_crossing_msg):
rospy.loginfo("LevelCrossing Step changed from %d", self.current_step_level_crossing)
self.current_step_level_crossing = level_crossing_msg.data
rospy.loginfo("into %d", self.current_step_level_crossing)
if self.current_step_level_crossing == self.StepOfLevelCrossing.pass_level.value:
self.current_mode = self.CurrentMode.level_crossing.value
msg_mode_return = UInt8()
msg_mode_return.data = self.current_mode
self.pub_mode_return.publish(msg_mode_return)
self.is_triggered = True
# Which step is in Tunnel
def cbTunnelStamped(self, tunnel_msg):
rospy.loginfo("Tunnel Step changed from %d", self.current_step_tunnel)
self.current_step_tunnel = tunnel_msg.data
rospy.loginfo("into %d", self.current_step_tunnel)
if self.current_step_tunnel == self.StepOfTunnel.searching_tunnel_sign.value:
self.current_mode = self.CurrentMode.tunnel.value
msg_mode_return = UInt8()
msg_mode_return.data = self.current_mode
self.pub_mode_return.publish(msg_mode_return)
self.is_triggered = True
def fnControlNode(self):
# lane_following
if self.current_mode == self.CurrentMode.lane_following.value:
rospy.loginfo("New trigger for lane_following")
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_parking.value, False)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
# traffic_light
elif self.current_mode == self.CurrentMode.traffic_light.value:
rospy.loginfo("New trigger for traffic_light")
msg_pub_traffic_light_order = UInt8()
if self.current_step_traffic_light == self.StepOfTrafficLight.searching_traffic_light.value:
rospy.loginfo("Current step : searching_traffic_light")
rospy.loginfo("Go to next step : in_traffic_light")
msg_pub_traffic_light_order.data = self.StepOfTrafficLight.in_traffic_light.value
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_parking.value, False)
self.fnLaunch(self.Launcher.launch_control_level.value, False)
elif self.current_step_traffic_light == self.StepOfTrafficLight.in_traffic_light.value:
rospy.loginfo("Current step : in_traffic_light")
rospy.loginfo("Go to next step : pass_traffic_light")
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_parking.value, False)
self.fnLaunch(self.Launcher.launch_control_level.value, False)
rospy.sleep(2)
self.pub_traffic_light_order.publish(msg_pub_traffic_light_order)
# parking_lot
elif self.current_mode == self.CurrentMode.parking_lot.value:
rospy.loginfo("New trigger for parking_lot")
msg_pub_parking_lot_order = UInt8()
if self.current_step_parking_lot == self.StepOfParkingLot.searching_parking_sign.value:
rospy.loginfo("Current step : searching_parking_sign")
rospy.loginfo("Go to next step : searching_parking_point_line")
msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_parking_point_line.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_parking.value, False)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_parking_lot == self.StepOfParkingLot.searching_parking_point_line.value:
rospy.loginfo("Current step : searching_parking_point_line")
rospy.loginfo("Go to next step : searching_nonreserved_parking_area")
msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_nonreserved_parking_area.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_parking.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_parking_lot == self.StepOfParkingLot.searching_nonreserved_parking_area.value:
rospy.loginfo("Current step : searching_nonreserved_parking_area")
rospy.loginfo("Go to next step : parking")
msg_pub_parking_lot_order.data = self.StepOfParkingLot.parking.value
self.fnLaunch(self.Launcher.launch_control_lane.value, False)
self.fnLaunch(self.Launcher.launch_control_parking.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_parking_lot == self.StepOfParkingLot.parking.value:
rospy.loginfo("Current step : parking")
rospy.loginfo("Go to next step : searching_parking_sign")
msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_parking_sign.value
self.fnLaunch(self.Launcher.launch_control_parking.value, False)
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
rospy.sleep(2)
self.pub_parking_lot_order.publish(msg_pub_parking_lot_order)
# level_crossing
elif self.current_mode == self.CurrentMode.level_crossing.value:
rospy.loginfo("New trigger for level_crossing")
msg_pub_level_crossing_order = UInt8()
if self.current_step_level_crossing == self.StepOfLevelCrossing.searching_stop_sign.value:
rospy.loginfo("Current step : searching_stop_sign")
rospy.loginfo("Go to next step : searching_level")
msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.searching_level.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_level_crossing == self.StepOfLevelCrossing.searching_level.value:
rospy.loginfo("Current step : searching_level")
rospy.loginfo("Go to next step : watching_level")
msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.watching_level.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_level_crossing == self.StepOfLevelCrossing.watching_level.value:
rospy.loginfo("Current step : watching_level")
rospy.loginfo("Go to next step : stop")
msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.stop.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_level_crossing == self.StepOfLevelCrossing.stop.value:
rospy.loginfo("Current step : stop")
rospy.loginfo("Go to next step : pass_level")
msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.pass_level.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_level_crossing == self.StepOfLevelCrossing.pass_level.value:
rospy.loginfo("Current step : pass_level")
rospy.loginfo("Go to next step : searching_stop_sign")
msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.searching_stop_sign.value
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
rospy.sleep(2)
self.pub_level_crossing_order.publish(msg_pub_level_crossing_order)
# tunnel
elif self.current_mode == self.CurrentMode.tunnel.value:
rospy.loginfo("New trigger for tunnel")
msg_pub_tunnel_order = UInt8()
if self.current_step_tunnel == self.StepOfTunnel.searching_tunnel_sign.value:
rospy.loginfo("Current step : searching_tunnel_sign")
rospy.loginfo("Go to next step : go_in_to_tunnel")
msg_pub_tunnel_order.data = self.StepOfTunnel.go_in_to_tunnel.value
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
self.fnLaunch(self.Launcher.launch_control_lane.value, False)
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, False)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
elif self.current_step_tunnel == self.StepOfTunnel.go_in_to_tunnel.value:
rospy.loginfo("Current step : go_in_to_tunnel")
rospy.loginfo("Go to next step : navigation")
msg_pub_tunnel_order.data = self.StepOfTunnel.navigation.value
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, False)
self.fnLaunch(self.Launcher.launch_control_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, True)
elif self.current_step_tunnel == self.StepOfTunnel.navigation.value:
rospy.loginfo("Current step : navigation")
rospy.loginfo("Go to next step : go_out_from_tunnel")
msg_pub_tunnel_order.data = self.StepOfTunnel.go_out_from_tunnel.value
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
self.fnLaunch(self.Launcher.launch_control_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
elif self.current_step_tunnel == self.StepOfTunnel.go_out_from_tunnel.value:
rospy.loginfo("Current step : go_out_from_tunnel")
rospy.loginfo("Go to next step : exit")
msg_pub_tunnel_order.data = self.StepOfTunnel.exit.value
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
elif self.current_step_tunnel == self.StepOfTunnel.exit.value:
rospy.loginfo("Current step : exit")
rospy.loginfo("Go to next step : searching_tunnel_sign")
msg_pub_tunnel_order.data = self.StepOfTunnel.searching_tunnel_sign.value
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
rospy.sleep(2)
self.pub_tunnel_order.publish(msg_pub_tunnel_order)
self.is_triggered = False
def fnLaunch(self, launch_num, is_start):
if launch_num == self.Launcher.launch_camera_ex_calib.value:
if is_start == True:
if self.launch_camera_launched == False:
self.launch_camera = roslaunch.scriptapi.ROSLaunch()
self.launch_camera = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_camera/launch/turtlebot3_autorace_extrinsic_camera_calibration.launch"])
self.launch_camera_launched = True
self.launch_camera.start()
else:
pass
else:
if self.launch_camera_launched == True:
self.launch_camera_launched = False
self.launch_camera.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_sign.value:
if is_start == True:
if self.launch_detect_sign_launched == False:
self.launch_detect_sign = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_sign = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_sign.launch"])
self.launch_detect_sign_launched = True
self.launch_detect_sign.start()
else:
pass
else:
if self.launch_detect_sign_launched == True:
self.launch_detect_sign_launched = False
self.launch_detect_sign.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_lane.value:
if is_start == True:
if self.launch_detect_lane_launched == False:
self.launch_detect_lane = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_lane = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_lane.launch"])
self.launch_detect_lane_launched = True
self.launch_detect_lane.start()
else:
pass
else:
if self.launch_detect_lane_launched == True:
self.launch_detect_lane_launched = False
self.launch_detect_lane.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_control_lane.value:
if is_start == True:
if self.launch_control_lane_launched == False:
self.launch_control_lane = roslaunch.scriptapi.ROSLaunch()
self.launch_control_lane = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_lane.launch"])
self.launch_control_lane_launched = True
self.launch_control_lane.start()
else:
pass
else:
if self.launch_control_lane_launched == True:
self.launch_control_lane_launched = False
self.launch_control_lane.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_parking.value:
if is_start == True:
if self.launch_detect_parking_launched == False:
self.launch_detect_parking = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_parking = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_parking.launch"])
self.launch_detect_parking_launched = True
self.launch_detect_parking.start()
else:
pass
else:
if self.launch_detect_parking_launched == True:
self.launch_detect_parking_launched = False
self.launch_detect_parking.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_control_parking.value:
if is_start == True:
if self.launch_control_parking_launched == False:
self.launch_control_parking = roslaunch.scriptapi.ROSLaunch()
self.launch_control_parking = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_parking.launch"])
self.launch_control_parking_launched = True
self.launch_control_parking.start()
else:
pass
else:
if self.launch_control_parking_launched == True:
self.launch_control_parking_launched = False
self.launch_control_parking.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_level.value:
if is_start == True:
if self.launch_detect_level_launched == False:
self.launch_detect_level = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_level = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_level.launch"])
self.launch_detect_level_launched = True
self.launch_detect_level.start()
else:
pass
else:
if self.launch_detect_level_launched == True:
self.launch_detect_level_launched = False
self.launch_detect_level.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_traffic_light.value:
if is_start == True:
if self.launch_detect_traffic_light_launched == False:
self.launch_detect_traffic_light = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_traffic_light = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_traffic_light.launch"])
self.launch_detect_traffic_light_launched = True
self.launch_detect_traffic_light.start()
else:
pass
else:
if self.launch_detect_traffic_light_launched == True:
self.launch_detect_traffic_light_launched = False
self.launch_detect_traffic_light.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_tunnel.value:
if is_start == True:
if self.launch_detect_tunnel_launched == False:
self.launch_detect_tunnel = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_tunnel = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_tunnel.launch"])
self.launch_detect_tunnel_launched = True
self.launch_detect_tunnel.start()
else:
pass
else:
if self.launch_detect_tunnel_launched == True:
self.launch_detect_tunnel_launched = False
self.launch_detect_tunnel.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_control_tunnel.value:
if is_start == True:
if self.launch_control_tunnel_launched == False:
self.launch_control_tunnel = roslaunch.scriptapi.ROSLaunch()
self.launch_control_tunnel = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_tunnel.launch"])
self.launch_control_tunnel_launched = True
self.launch_control_tunnel.start()
else:
pass
else:
if self.launch_control_tunnel_launched == True:
self.launch_control_tunnel_launched = False
self.launch_control_tunnel.shutdown()
else:
pass
def main(self):
rospy.spin()
if __name__ == '__main__':
rospy.init_node('core_node_controller')
node = CoreNodeController()
node.main()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright 2018 ROBOTIS CO., LTD.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://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.
################################################################################
# Authors: Leon Jung, [AuTURBO] Kihoon Kim (https://github.com/auturbo), Gilbert
import rospy, roslaunch
import numpy as np
import subprocess
import os
import sys
from enum import Enum
from std_msgs.msg import UInt8
class CoreNodeController():
def __init__(self):
self.ros_package_path = os.path.dirname(os.path.realpath(__file__))
self.ros_package_path = self.ros_package_path.replace('turtlebot3_autorace_core/nodes', '')
self.sub_mode_control = rospy.Subscriber('/core/decided_mode', UInt8, self.cbReceiveMode, queue_size=1)
self.CurrentMode = Enum('CurrentMode', 'idle lane_following traffic_light parking_lot level_crossing tunnel')
# subscribes : status returned
self.sub_parking_lot_stamped = rospy.Subscriber('/detect/parking_lot_stamped', UInt8, self.cbParkingLotStamped, queue_size=1)
self.sub_level_crossing_stamped = rospy.Subscriber('/detect/level_crossing_stamped', UInt8, self.cbLevelCrossingStamped, queue_size=1)
self.sub_tunnel_stamped = rospy.Subscriber('/detect/tunnel_stamped', UInt8, self.cbTunnelStamped, queue_size=1)
# publishes orders
self.pub_traffic_light_order = rospy.Publisher('/detect/traffic_light_order', UInt8, queue_size=1)
self.pub_parking_lot_order = rospy.Publisher('/detect/parking_lot_order', UInt8, queue_size=1)
self.pub_level_crossing_order = rospy.Publisher('/detect/level_crossing_order', UInt8, queue_size=1)
self.pub_tunnel_order = rospy.Publisher('/detect/tunnel_order', UInt8, queue_size=1)
self.pub_mode_return = rospy.Publisher('/core/returned_mode', UInt8, queue_size=1)
self.StepOfParkingLot = Enum('StepOfParkingLot', 'searching_parking_sign searching_parking_point_line searching_nonreserved_parking_area parking')
self.StepOfLevelCrossing = Enum('StepOfLevelCrossing', 'searching_stop_sign searching_level watching_level stop pass_level')
self.StepOfTunnel = Enum('StepOfTunnel', 'searching_tunnel_sign go_in_to_tunnel navigation go_out_from_tunnel exit')
self.current_step_parking_lot = self.StepOfParkingLot.searching_parking_sign.value
self.current_step_level_crossing = self.StepOfLevelCrossing.searching_stop_sign.value
self.current_step_tunnel = self.StepOfTunnel.searching_tunnel_sign.value
self.Launcher = Enum('Launcher', 'launch_camera_ex_calib launch_detect_sign launch_detect_lane launch_control_lane launch_detect_traffic_light launch_control_traffic_light launch_detect_parking launch_control_parking launch_detect_level launch_control_level launch_detect_tunnel launch_control_tunnel')
self.uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)
self.launch_camera_launched = False
self.launch_detect_sign_launched = False
self.launch_detect_lane_launched = False
self.launch_control_lane_launched = False
self.launch_detect_parking_launched = False
self.launch_control_parking_launched = False
self.launch_detect_level_launched = False
self.launch_detect_traffic_light_launched = False
self.launch_detect_tunnel_launched = False
self.launch_control_tunnel_launched = False
self.current_mode = self.CurrentMode.idle.value
self.is_triggered = False
loop_rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
if self.is_triggered == True:
self.fnControlNode()
loop_rate.sleep()
def cbReceiveMode(self, mode_msg):
rospy.loginfo("starts the progress with %d", mode_msg.data)
self.current_mode = mode_msg.data
self.is_triggered = True
# Which step is in Parking Lot
def cbParkingLotStamped(self, parking_lot_msg):
rospy.loginfo("ParkingLot Step changed from %d", self.current_step_parking_lot)
self.current_step_parking_lot = parking_lot_msg.data
rospy.loginfo("into %d", self.current_step_parking_lot)
if self.current_step_parking_lot == self.StepOfParkingLot.parking.value:
self.current_mode = self.CurrentMode.lane_following.value
msg_mode_return = UInt8()
msg_mode_return.data = self.current_mode
self.current_step_parking_lot = self.StepOfParkingLot.searching_parking_sign.value
rospy.loginfo("pub_mode_return")
self.pub_mode_return.publish(msg_mode_return)
self.is_triggered = True
# Which step is in Level Crossing
def cbLevelCrossingStamped(self, level_crossing_msg):
rospy.loginfo("LevelCrossing Step changed from %d", self.current_step_level_crossing)
self.current_step_level_crossing = level_crossing_msg.data
rospy.loginfo("into %d", self.current_step_level_crossing)
if self.current_step_level_crossing == self.StepOfLevelCrossing.pass_level.value:
self.current_mode = self.CurrentMode.level_crossing.value
msg_mode_return = UInt8()
msg_mode_return.data = self.current_mode
self.pub_mode_return.publish(msg_mode_return)
self.is_triggered = True
# Which step is in Tunnel
def cbTunnelStamped(self, tunnel_msg):
rospy.loginfo("Tunnel Step changed from %d", self.current_step_tunnel)
self.current_step_tunnel = tunnel_msg.data
rospy.loginfo("into %d", self.current_step_tunnel)
if self.current_step_tunnel == self.StepOfTunnel.searching_tunnel_sign.value:
self.current_mode = self.CurrentMode.tunnel.value
msg_mode_return = UInt8()
msg_mode_return.data = self.current_mode
self.pub_mode_return.publish(msg_mode_return)
self.is_triggered = True
def fnControlNode(self):
# lane_following
if self.current_mode == self.CurrentMode.lane_following.value:
rospy.loginfo("New trigger for lane_following")
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_parking.value, False)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
# traffic_light
elif self.current_mode == self.CurrentMode.traffic_light.value:
rospy.loginfo("New trigger for traffic_light")
msg_pub_traffic_light_order = UInt8()
if self.current_step_traffic_light == self.StepOfTrafficLight.searching_traffic_light.value:
rospy.loginfo("Current step : searching_traffic_light")
rospy.loginfo("Go to next step : in_traffic_light")
msg_pub_traffic_light_order.data = self.StepOfTrafficLight.in_traffic_light.value
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_parking.value, False)
self.fnLaunch(self.Launcher.launch_control_level.value, False)
elif self.current_step_traffic_light == self.StepOfTrafficLight.in_traffic_light.value:
rospy.loginfo("Current step : in_traffic_light")
rospy.loginfo("Go to next step : pass_traffic_light")
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_parking.value, False)
self.fnLaunch(self.Launcher.launch_control_level.value, False)
rospy.sleep(2)
self.pub_traffic_light_order.publish(msg_pub_traffic_light_order)
# parking_lot
elif self.current_mode == self.CurrentMode.parking_lot.value:
rospy.loginfo("New trigger for parking_lot")
msg_pub_parking_lot_order = UInt8()
if self.current_step_parking_lot == self.StepOfParkingLot.searching_parking_sign.value:
rospy.loginfo("Current step : searching_parking_sign")
rospy.loginfo("Go to next step : searching_parking_point_line")
msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_parking_point_line.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_parking.value, False)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_parking_lot == self.StepOfParkingLot.searching_parking_point_line.value:
rospy.loginfo("Current step : searching_parking_point_line")
rospy.loginfo("Go to next step : searching_nonreserved_parking_area")
msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_nonreserved_parking_area.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_parking.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_parking_lot == self.StepOfParkingLot.searching_nonreserved_parking_area.value:
rospy.loginfo("Current step : searching_nonreserved_parking_area")
rospy.loginfo("Go to next step : parking")
msg_pub_parking_lot_order.data = self.StepOfParkingLot.parking.value
self.fnLaunch(self.Launcher.launch_control_lane.value, False)
self.fnLaunch(self.Launcher.launch_control_parking.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_parking_lot == self.StepOfParkingLot.parking.value:
rospy.loginfo("Current step : parking")
rospy.loginfo("Go to next step : searching_parking_sign")
msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_parking_sign.value
self.fnLaunch(self.Launcher.launch_control_parking.value, False)
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
rospy.sleep(2)
self.pub_parking_lot_order.publish(msg_pub_parking_lot_order)
# level_crossing
elif self.current_mode == self.CurrentMode.level_crossing.value:
rospy.loginfo("New trigger for level_crossing")
msg_pub_level_crossing_order = UInt8()
if self.current_step_level_crossing == self.StepOfLevelCrossing.searching_stop_sign.value:
rospy.loginfo("Current step : searching_stop_sign")
rospy.loginfo("Go to next step : searching_level")
msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.searching_level.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_level_crossing == self.StepOfLevelCrossing.searching_level.value:
rospy.loginfo("Current step : searching_level")
rospy.loginfo("Go to next step : watching_level")
msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.watching_level.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_level_crossing == self.StepOfLevelCrossing.watching_level.value:
rospy.loginfo("Current step : watching_level")
rospy.loginfo("Go to next step : stop")
msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.stop.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_level_crossing == self.StepOfLevelCrossing.stop.value:
rospy.loginfo("Current step : stop")
rospy.loginfo("Go to next step : pass_level")
msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.pass_level.value
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
elif self.current_step_level_crossing == self.StepOfLevelCrossing.pass_level.value:
rospy.loginfo("Current step : pass_level")
rospy.loginfo("Go to next step : searching_stop_sign")
msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.searching_stop_sign.value
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
rospy.sleep(2)
self.pub_level_crossing_order.publish(msg_pub_level_crossing_order)
# tunnel
elif self.current_mode == self.CurrentMode.tunnel.value:
rospy.loginfo("New trigger for tunnel")
msg_pub_tunnel_order = UInt8()
if self.current_step_tunnel == self.StepOfTunnel.searching_tunnel_sign.value:
rospy.loginfo("Current step : searching_tunnel_sign")
rospy.loginfo("Go to next step : go_in_to_tunnel")
msg_pub_tunnel_order.data = self.StepOfTunnel.go_in_to_tunnel.value
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
self.fnLaunch(self.Launcher.launch_control_lane.value, False)
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, False)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
elif self.current_step_tunnel == self.StepOfTunnel.go_in_to_tunnel.value:
rospy.loginfo("Current step : go_in_to_tunnel")
rospy.loginfo("Go to next step : navigation")
msg_pub_tunnel_order.data = self.StepOfTunnel.navigation.value
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, False)
self.fnLaunch(self.Launcher.launch_control_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, True)
elif self.current_step_tunnel == self.StepOfTunnel.navigation.value:
rospy.loginfo("Current step : navigation")
rospy.loginfo("Go to next step : go_out_from_tunnel")
msg_pub_tunnel_order.data = self.StepOfTunnel.go_out_from_tunnel.value
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
self.fnLaunch(self.Launcher.launch_control_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
elif self.current_step_tunnel == self.StepOfTunnel.go_out_from_tunnel.value:
rospy.loginfo("Current step : go_out_from_tunnel")
rospy.loginfo("Go to next step : exit")
msg_pub_tunnel_order.data = self.StepOfTunnel.exit.value
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
elif self.current_step_tunnel == self.StepOfTunnel.exit.value:
rospy.loginfo("Current step : exit")
rospy.loginfo("Go to next step : searching_tunnel_sign")
msg_pub_tunnel_order.data = self.StepOfTunnel.searching_tunnel_sign.value
self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
self.fnLaunch(self.Launcher.launch_control_lane.value, True)
self.fnLaunch(self.Launcher.launch_detect_level.value, False)
self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
rospy.sleep(2)
self.pub_tunnel_order.publish(msg_pub_tunnel_order)
self.is_triggered = False
def fnLaunch(self, launch_num, is_start):
if launch_num == self.Launcher.launch_camera_ex_calib.value:
if is_start == True:
if self.launch_camera_launched == False:
self.launch_camera = roslaunch.scriptapi.ROSLaunch()
self.launch_camera = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_camera/launch/turtlebot3_autorace_extrinsic_camera_calibration.launch"])
self.launch_camera_launched = True
self.launch_camera.start()
else:
pass
else:
if self.launch_camera_launched == True:
self.launch_camera_launched = False
self.launch_camera.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_sign.value:
if is_start == True:
if self.launch_detect_sign_launched == False:
self.launch_detect_sign = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_sign = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_sign.launch"])
self.launch_detect_sign_launched = True
self.launch_detect_sign.start()
else:
pass
else:
if self.launch_detect_sign_launched == True:
self.launch_detect_sign_launched = False
self.launch_detect_sign.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_lane.value:
if is_start == True:
if self.launch_detect_lane_launched == False:
self.launch_detect_lane = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_lane = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_lane.launch"])
self.launch_detect_lane_launched = True
self.launch_detect_lane.start()
else:
pass
else:
if self.launch_detect_lane_launched == True:
self.launch_detect_lane_launched = False
self.launch_detect_lane.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_control_lane.value:
if is_start == True:
if self.launch_control_lane_launched == False:
self.launch_control_lane = roslaunch.scriptapi.ROSLaunch()
self.launch_control_lane = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_lane.launch"])
self.launch_control_lane_launched = True
self.launch_control_lane.start()
else:
pass
else:
if self.launch_control_lane_launched == True:
self.launch_control_lane_launched = False
self.launch_control_lane.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_parking.value:
if is_start == True:
if self.launch_detect_parking_launched == False:
self.launch_detect_parking = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_parking = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_parking.launch"])
self.launch_detect_parking_launched = True
self.launch_detect_parking.start()
else:
pass
else:
if self.launch_detect_parking_launched == True:
self.launch_detect_parking_launched = False
self.launch_detect_parking.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_control_parking.value:
if is_start == True:
if self.launch_control_parking_launched == False:
self.launch_control_parking = roslaunch.scriptapi.ROSLaunch()
self.launch_control_parking = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_parking.launch"])
self.launch_control_parking_launched = True
self.launch_control_parking.start()
else:
pass
else:
if self.launch_control_parking_launched == True:
self.launch_control_parking_launched = False
self.launch_control_parking.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_level.value:
if is_start == True:
if self.launch_detect_level_launched == False:
self.launch_detect_level = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_level = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_level.launch"])
self.launch_detect_level_launched = True
self.launch_detect_level.start()
else:
pass
else:
if self.launch_detect_level_launched == True:
self.launch_detect_level_launched = False
self.launch_detect_level.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_traffic_light.value:
if is_start == True:
if self.launch_detect_traffic_light_launched == False:
self.launch_detect_traffic_light = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_traffic_light = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_traffic_light.launch"])
self.launch_detect_traffic_light_launched = True
self.launch_detect_traffic_light.start()
else:
pass
else:
if self.launch_detect_traffic_light_launched == True:
self.launch_detect_traffic_light_launched = False
self.launch_detect_traffic_light.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_detect_tunnel.value:
if is_start == True:
if self.launch_detect_tunnel_launched == False:
self.launch_detect_tunnel = roslaunch.scriptapi.ROSLaunch()
self.launch_detect_tunnel = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_tunnel.launch"])
self.launch_detect_tunnel_launched = True
self.launch_detect_tunnel.start()
else:
pass
else:
if self.launch_detect_tunnel_launched == True:
self.launch_detect_tunnel_launched = False
self.launch_detect_tunnel.shutdown()
else:
pass
elif launch_num == self.Launcher.launch_control_tunnel.value:
if is_start == True:
if self.launch_control_tunnel_launched == False:
self.launch_control_tunnel = roslaunch.scriptapi.ROSLaunch()
self.launch_control_tunnel = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_tunnel.launch"])
self.launch_control_tunnel_launched = True
self.launch_control_tunnel.start()
else:
pass
else:
if self.launch_control_tunnel_launched == True:
self.launch_control_tunnel_launched = False
self.launch_control_tunnel.shutdown()
else:
pass
def main(self):
rospy.spin()
if __name__ == '__main__':
rospy.init_node('core_node_controller')
node = CoreNodeController()
node.main()
from ament_index_python import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
import os
def generate_launch_description():
aichallenge_sample_pkg_prefix = get_package_share_directory('aichallenge_sample')
aichallenge_sample_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource([aichallenge_sample_pkg_prefix, '/launch/aichallenge_sample.launch.py']),
launch_arguments={}.items()
)
return LaunchDescription([
aichallenge_sample_launch,
])
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LaunchUIComponent = undefined;
var _string;
function _load_string() {
return _string = require('nuclide-commons/string');
}
var _react = _interopRequireDefault(require('react'));
var _AtomInput;
function _load_AtomInput() {
return _AtomInput = require('nuclide-commons-ui/AtomInput');
}
var _UniversalDisposable;
function _load_UniversalDisposable() {
return _UniversalDisposable = _interopRequireDefault(require('nuclide-commons/UniversalDisposable'));
}
var _nuclideUri;
function _load_nuclideUri() {
return _nuclideUri = _interopRequireDefault(require('nuclide-commons/nuclideUri'));
}
var _nuclideDebuggerBase;
function _load_nuclideDebuggerBase() {
return _nuclideDebuggerBase = require('../../nuclide-debugger-base');
}
var _classnames;
function _load_classnames() {
return _classnames = _interopRequireDefault(require('classnames'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class LaunchUIComponent extends _react.default.Component {
constructor(props) {
super(props);
this._handleLaunchClick = () => {
// TODO: perform some validation for the input.
const launchExecutable = this.refs.launchExecutable.getText().trim();
const coreDump = this.refs.coreDump.getText().trim();
const launchArguments = (0, (_string || _load_string()).shellParse)(this.refs.launchArguments.getText());
const launchEnvironmentVariables = (0, (_string || _load_string()).shellParse)(this.refs.launchEnvironmentVariables.getText());
const launchWorkingDirectory = this.refs.launchWorkingDirectory.getText().trim();
const stdinFilePath = this.refs.stdinFilePath.getText().trim();
const launchTarget = {
executablePath: launchExecutable,
arguments: launchArguments,
environmentVariables: launchEnvironmentVariables,
workingDirectory: launchWorkingDirectory,
stdinFilePath,
coreDump
};
// Fire and forget.
this.props.actions.launchDebugger(launchTarget);
(0, (_nuclideDebuggerBase || _load_nuclideDebuggerBase()).serializeDebuggerConfig)(...this._getSerializationArgs(), {
launchExecutable: this.state.launchExecutable,
launchArguments: this.state.launchArguments,
launchEnvironmentVariables: this.state.launchEnvironmentVariables,
launchWorkingDirectory: this.state.launchWorkingDirectory,
stdinFilePath: this.state.stdinFilePath,
coreDump: this.state.coreDump
});
};
this._disposables = new (_UniversalDisposable || _load_UniversalDisposable()).default();
this.state = {
launchExecutable: '',
launchArguments: '',
launchEnvironmentVariables: '',
launchWorkingDirectory: '',
stdinFilePath: '',
coreDump: ''
};
}
_getSerializationArgs() {
return [(_nuclideUri || _load_nuclideUri()).default.isRemote(this.props.targetUri) ? (_nuclideUri || _load_nuclideUri()).default.getHostname(this.props.targetUri) : 'local', 'launch', 'native'];
}
setState(newState) {
super.setState(newState);
this.props.configIsValidChanged(this._debugButtonShouldEnable());
}
_debugButtonShouldEnable() {
return true;
}
componentDidMount() {
(0, (_nuclideDebuggerBase || _load_nuclideDebuggerBase()).deserializeDebuggerConfig)(...this._getSerializationArgs(), (transientSettings, savedSettings) => {
this.setState({
launchExecutable: savedSettings.launchExecutable,
launchArguments: savedSettings.launchArguments,
launchEnvironmentVariables: savedSettings.launchEnvironmentVariables,
launchWorkingDirectory: savedSettings.launchWorkingDirectory,
stdinFilePath: savedSettings.stdinFilePath,
coreDump: savedSettings.coreDump || ''
});
});
const launchExecutableInput = this.refs.launchExecutable;
if (launchExecutableInput != null) {
launchExecutableInput.focus();
}
this._disposables.add(atom.commands.add('atom-workspace', {
'core:confirm': () => {
this._handleLaunchClick();
}
}));
this.props.configIsValidChanged(true);
}
componentWillUnmount() {
this._disposables.dispose();
}
render() {
// TODO: smart fill the working directory textbox.
// TODO: make tab stop between textbox work.
// Reserve tabIndex [1~10] to header portion of the UI so we start from "11" here.
return _react.default.createElement(
'div',
{ className: 'block' },
_react.default.createElement(
'label',
null,
'Executable: '
),
_react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
ref: 'launchExecutable',
tabIndex: '11',
placeholderText: 'Input the executable path you want to launch',
value: this.state.launchExecutable,
onDidChange: value => this.setState({ launchExecutable: value })
}),
_react.default.createElement(
'label',
null,
'Core dump file: '
),
_react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
ref: 'coreDump',
tabIndex: '12',
placeholderText: 'Optional path to a core dump file to offline debug a crash',
value: this.state.coreDump,
onDidChange: value => this.setState({ coreDump: value })
}),
_react.default.createElement(
'div',
{ className: 'nuclide-native-launch-small-text' },
'Be sure to copy the core dump to a location where Nuclide has read access. (Nuclide server does not run as root).'
),
_react.default.createElement(
'div',
{
className: (0, (_classnames || _load_classnames()).default)({
'nuclide-native-launch-disabled': this.state.coreDump !== ''
}) },
_react.default.createElement(
'label',
null,
'Arguments: '
),
_react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
ref: 'launchArguments',
tabIndex: '13',
disabled: this.state.coreDump !== '',
placeholderText: 'Arguments to the executable',
value: this.state.launchArguments,
onDidChange: value => this.setState({ launchArguments: value })
}),
_react.default.createElement(
'label',
null,
'Environment Variables: '
),
_react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
ref: 'launchEnvironmentVariables',
tabIndex: '14',
disabled: this.state.coreDump !== '',
placeholderText: 'Environment variables (e.g., SHELL=/bin/bash PATH=/bin)',
value: this.state.launchEnvironmentVariables,
onDidChange: value => this.setState({ launchEnvironmentVariables: value })
}),
_react.default.createElement(
'label',
null,
'Working directory: '
),
_react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
ref: 'launchWorkingDirectory',
tabIndex: '15',
disabled: this.state.coreDump !== '',
placeholderText: 'Working directory for the launched executable',
value: this.state.launchWorkingDirectory,
onDidChange: value => this.setState({ launchWorkingDirectory: value })
}),
_react.default.createElement(
'label',
null,
'Stdin file: '
),
_react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
ref: 'stdinFilePath',
tabIndex: '16',
disabled: this.state.coreDump !== '',
placeholderText: 'Redirect stdin to this file',
value: this.state.stdinFilePath,
onDidChange: value => this.setState({ stdinFilePath: value })
})
)
);
}
}
exports.LaunchUIComponent = LaunchUIComponent; /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the LICENSE file in
* the root directory of this source tree.
*
*
* @format
*/
// Copyright (c) 2009-2017 SAP SE, All Rights Reserved
/**
* @fileOverview QUnit tests for sap.ushell.services.LaunchPage
*/
sap.ui.require([
"sap/ushell/services/LaunchPage",
"sap/ushell/test/utils",
"sap/ushell/adapters/local/LaunchPageAdapter",
"sap/ushell/Config",
"sap/ushell/services/_ContentExtensionAdapterFactory/ContentExtensionAdapterConfig",
"sap/ushell/services/_ContentExtensionAdapterFactory/FeaturedGroupConfig",
"sap/ushell/resources"
], function (LaunchPage, testUtils, LaunchPageAdapter, Config, AdapterFactoryConfig, FeaturedGroupMock) {
"use strict";
/*global asyncTest, deepEqual, module, throws ok, start, strictEqual, test, sinon */
var sUshellTestRootPath = jQuery.sap.getResourcePath("sap/ushell").replace("resources", "test-resources"),
oLastStub,
oGetMockAdapterConfigStub,
oGetConfigAdaptersStub,
oLaunchPageConfig = {
config: {
pathToLocalizedContentResources: sUshellTestRootPath + "/test/services/resources/resources.properties",
groups: [{
id: "group_0",
title: "test_group1",
isPreset: true,
isVisible: true,
isGroupLocked: false,
tiles: [{
id: "9a6eb46c-2d10-3a37-90d8-8f49f60cb111",
title: "test_tile_header",
size: "1x1",
tileType: "sap.ushell.ui.tile.TileBase",
keywords: ["test_keywords"],
properties: {
chipId: "catalogTile_1",
title: "test_tile_header",
subtitle: "test_sub_tile_header",
infoState: "Neutral",
info: "test_info",
icon: "sap-icon://travel-expense-report",
targetURL: "#Action-todefaultapp",
formFactor: "Desktop,Tablet,Phone"
}
},
{
id: "tile_001",
title: "test_tile_preview_api",
size: "1x1",
tileType: "sap.ushell.ui.tile.TileBase",
keywords: ["test_keywords"],
properties: {
chipId: "catalogTile_1",
infoState: "Neutral",
info: "test_info",
formFactor: "Desktop,Tablet,Phone"
}
},
{
id: "tile_787",
tileType: "sap.ushell.ui.tile.StaticTile",
isLink: true,
properties: {
text: "I am a link!",
href: "#Action-todefaultapp"
}
},
{
id: "tile_777",
tileType: "sap.ushell.ui.tile.StaticTile",
isLink: true,
properties: {
text: "I am an external link!",
href: "http://www.google.com"
}
},
{
id: "tile_797",
tileType: "sap.ushell.ui.tile.StaticTile",
mode: "HeaderMode",
properties: {
title: "test_tile_header",
subtitle: "test_sub_tile_header"
}
},
{
id: "tile_807",
tileType: "sap.ushell.ui.tile.StaticTile",
mode: "ContentMode",
properties: {
title: "test_tile_header",
subtitle: "test_sub_tile_header"
}
}
]
}, {
id: "group_1",
title: "test_group2",
isPreset: true,
isVisible: true,
isGroupLocked: false,
tiles: [{}]
}, {
id: "group_2",
title: "test_group3",
isPreset: true,
isVisible: true,
isGroupLocked: false,
tiles: [
{
id: "tile_102",
title: "Test component tile",
size: "1x1",
tileType: "sap.ushell.ui.tile.StaticTile",
moduleName: "sap.ushell.demo.demoTiles",
moduleType: "UIComponent",
namespace: "sap.ushell.demo.demoTiles",
path: sUshellTestRootPath + "/demoapps/demoTiles/",
properties: {
chipId: "catalogTile_38",
title: "Test component tile",
subtitle: "A tile wrapped in a component",
infoState: "Neutral",
info: "0 days running without bugs",
icon: "sap-icon://flight",
targetURL: "#Action-todefaultapp",
formFactor: "Desktop,Tablet"
}
},
{
id: "tile_103",
title: "Test view tile",
size: "1x1",
tileType: "sap.ushell.ui.tile.StaticTile",
moduleName: "sap.ushell.demo.demoTiles.TestViewTile",
moduleType: "JS",
namespace: "sap.ushell.demo.demoTiles",
path: sUshellTestRootPath + "/demoapps/demoTiles/",
properties: {
chipId: "catalogTile_38",
title: "Test view tile",
subtitle: "A tile wrapped in a view",
infoState: "Neutral",
info: "0 days running without bugs",
icon: "sap-icon://flight",
targetURL: "#Action-todefaultapp",
formFactor: "Desktop,Tablet"
}
}
]
}, {
id: "group_3",
title: "test_group4",
isPreset: true,
isVisible: true,
isGroupLocked: true,
tiles: [{}]
}, {
id: "group_4",
title: "test_group5",
isPreset: true,
isVisible: false,
isGroupLocked: true,
tiles: [{}]
}],
catalogs: [
{
id: "test_catalog_01",
title: "test_catalog1",
tiles: [{}]
}, {
id: "test_catalog_02",
title: "test_catalog2",
tiles: [{}]
}
]
}
},
aAdditionalAdapterConfig = [{
name: "feature",
adapter: "sap.ushell.adapters.local.LaunchPageAdapter",
config: "/core/home/featuredGroup/enable",
system: {
alias: "",
platform: "local"
},
configHandler: function () {
var bEnableFrequentCard = true,
bEnableRecentCard = true;
return FeaturedGroupMock.getMockAdapterConfig(bEnableFrequentCard, bEnableRecentCard);
}
}],
oFeatureGroupConfig = {
groups: [{
"id": "featuredArea",
"contentProvider": "feature",
"isPersonalizationLocked": function () {
return true;
},
"getTitle": function () {
return "Featured";
},
"title": "Featured",
"isFeatured": true,
"isPreset": true,
"isVisible": true,
"isDefaultGroup": false,
"isGroupLocked": true,
"tiles": [{
"id": "tile_00",
"contentProvider": "feature",
"type": "recent",
"title": "[FEATURED] Sales Performance",
"text": "[FEATURED] Sales Performance",
"size": "1x1",
"tileType": "sap.ushell.ui.tile.DynamicTile",
"isLinkPersonalizationSupported": false,
"keywords": ["sales", "performance"],
"formFactor": "Desktop,Tablet,Phone",
"serviceRefreshInterval": 10,
"actions": [{
"text": "Go To Sample App",
"icon": "sap-icon://action",
"targetURL": "#Action-toappnavsample"
}, {
"text": "Go to stackoverflow",
"icon": "sap-icon://action",
"targetURL": "http://stackoverflow.com/"
}, {
"text": "Illigal URL",
"icon": "sap-icon://action",
"targetURL": "stackoverflow.com/"
}, {
"text": "Callback action",
"icon": "sap-icon://action-settings"
}],
"chipId": "catalogTile_33",
"properties": {
"title": "[FEATURED] Sales Performance",
"numberValue": 3.75,
"info": "Change to Last Month in %",
"numberFactor": "%",
"numberDigits": 2,
"numberState": "Positive",
"stateArrow": "Up",
"icon": "sap-icon://Fiori2/F0002",
"targetURL": "#Action-toappnavsample"
}
}, {
"id": "tile_shelluiservicesample",
"contentProvider": "feature",
"type": "frequent",
"title": "[FEATURED] ShellUIService Sample App",
"size": "1x1",
"tileType": "sap.ushell.ui.tile.StaticTile",
"isLinkPersonalizationSupported": true,
"formFactor": "Desktop,Tablet",
"chipId": "catalogTile_45",
"properties": {
"title": "[FEATURED] Sample App for ShellUIService",
"text": "[FEATURED] Sample App for ShellUIService",
"subtitle": "",
"infoState": "Neutral",
"info": "#Action-toappshelluiservicesample",
"icon": "sap-icon://syringe",
"targetURL": "#Action-toappshelluiservicesample"
}
}]
}]
};
[
{
testDescription: "when enableFeaturedGroup is true",
input: {
enableFeaturedGroup: true
},
output: {
numberOfFeaturedGroups: 1
}
},
{
testDescription: "when enableFeaturedGroup is false",
input: {
enableFeaturedGroup: false
},
output: {
numberOfFeaturedGroups: 0
}
}
].forEach(function (oFixture) {
module("sap.ushell.services.LaunchPage " + oFixture.testDescription, {
beforeEach: function (assert) {
oLastStub = sinon.stub(Config, 'last');
oLastStub.withArgs("/core/spaces/enabled").returns(false);
oLastStub.returns(oFixture.input.enableFeaturedGroup);
oGetMockAdapterConfigStub = sinon.stub(FeaturedGroupMock, "getMockAdapterConfig").returns(
oFeatureGroupConfig
);
oGetConfigAdaptersStub = sinon.stub(AdapterFactoryConfig, "_getConfigAdapters").returns(
aAdditionalAdapterConfig
);
},
teardown: function () {
testUtils.restoreSpies(
);
oLastStub.restore();
oGetMockAdapterConfigStub.restore();
oGetConfigAdaptersStub.restore();
}
});
test("addBookmark failures", function () {
var oLaunchPageService = new LaunchPage();
// code under test and tests
throws(function () {
oLaunchPageService.addBookmark();
});
throws(function () {
oLaunchPageService.addBookmark("Test");
});
throws(function () {
oLaunchPageService.addBookmark({});
}, /Title missing in bookmark configuration/);
throws(function () {
oLaunchPageService.addBookmark({title: ""});
}, /Title missing in bookmark configuration/);
throws(function () {
oLaunchPageService.addBookmark({title: "MyTitle"});
}, /URL missing in bookmark configuration/);
});
test("addBookmark success", function () {
var oActualPromise,
oBookmarkConfig = { title: "MyTitle", url: "MyUrl" },
oLaunchPageAdapter = {
addBookmark: sinon.stub().returns(new jQuery.Deferred().promise())
},
oLaunchPageService;
// prepare test
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
// code under test
oActualPromise = oLaunchPageService.addBookmark(oBookmarkConfig);
// test
ok(oLaunchPageAdapter.addBookmark.calledOnce);
ok(oLaunchPageAdapter.addBookmark.calledWith(oBookmarkConfig));
strictEqual(oActualPromise, oLaunchPageAdapter.addBookmark.returnValues[0]);
});
test("setTileVisible", function () {
var oTile = {},
oLaunchPageAdapter = {
setTileVisible: sinon.spy()
},
oLaunchPageService;
// prepare test
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
// code under test
oLaunchPageService.setTileVisible(oTile, true);
// test
ok(oLaunchPageAdapter.setTileVisible.calledOnce);
ok(oLaunchPageAdapter.setTileVisible.calledWithExactly(oTile, true));
});
test("getCatalogError", function () {
var oCatalog = {},
oLaunchPageAdapter = {
getCatalogError: sinon.stub().returns("foo")
},
oLaunchPageService;
// prepare test
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
// code under test
strictEqual(oLaunchPageService.getCatalogError(oCatalog), "foo");
// test
ok(oLaunchPageAdapter.getCatalogError.calledOnce);
ok(oLaunchPageAdapter.getCatalogError.calledWithExactly(oCatalog));
});
test("isTileIntentSupported", function () {
var oTile = {},
oLaunchPageAdapter = {
isTileIntentSupported: sinon.stub().returns("foo") // deliberately no boolean
},
oLaunchPageService;
// part 1: unsupported in adapter
oLaunchPageService = new LaunchPage({});
strictEqual(oLaunchPageService.isTileIntentSupported(oTile), true);
// part 2: delegates to adapter
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
strictEqual(oLaunchPageService.isTileIntentSupported(oTile), "foo");
ok(oLaunchPageAdapter.isTileIntentSupported.calledOnce);
ok(oLaunchPageAdapter.isTileIntentSupported.calledWithExactly(oTile));
});
test("getCardManifest", function () {
var oCard = {},
oLaunchPageAdapter = {
getCardManifest: sinon.stub().returns("Manifest")
},
oLaunchPageService;
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
strictEqual(oLaunchPageService.getCardManifest(oCard), "Manifest");
ok(oLaunchPageAdapter.getCardManifest.calledOnce);
ok(oLaunchPageAdapter.getCardManifest.calledWithExactly(oCard));
});
test("isGroupVisible", function () {
var oGroup = {},
oLaunchPageAdapter = {
isGroupVisible: sinon.stub().returns("visible")
},
oLaunchPageService;
// part 1: unsupported in adapter - default value received from the service directly
oLaunchPageService = new LaunchPage({});
strictEqual(oLaunchPageService.isGroupVisible(oGroup), true);
// part 2: delegates to adapter
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
strictEqual(oLaunchPageService.isGroupVisible(oGroup), "visible");
ok(oLaunchPageAdapter.isGroupVisible.calledOnce);
ok(oLaunchPageAdapter.isGroupVisible.calledWithExactly(oGroup));
});
test("isGroupLocked", function () {
var oGroup = {},
oLaunchPageAdapter = {
isGroupLocked: sinon.stub().returns("foo")
},
oLaunchPageService;
// part 1: unsupported in adapter - default value received from the service directly
oLaunchPageService = new LaunchPage({});
strictEqual(oLaunchPageService.isGroupLocked(oGroup), false);
// part 2: delegates to adapter
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
strictEqual(oLaunchPageService.isGroupLocked(oGroup), "foo");
ok(oLaunchPageAdapter.isGroupLocked.calledOnce);
ok(oLaunchPageAdapter.isGroupLocked.calledWithExactly(oGroup));
});
test("hideGroups", function () {
var aGroups = [],
oLaunchPageAdapter = {
hideGroups: sinon.stub().returns({
fail: function (f) {},
done: function (f) { return this; }
})
},
oLaunchPageService;
// part 1: unsupported in adapter - A deferred object is expected which is in failed status
oLaunchPageService = new LaunchPage({});
var oDeferred = oLaunchPageService.hideGroups([]);
strictEqual(oDeferred.state(), "rejected");
// part 2: delegates to adapter
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.hideGroups(aGroups);
ok(oLaunchPageAdapter.hideGroups.calledOnce);
ok(oLaunchPageAdapter.hideGroups.calledWithExactly(aGroups));
});
test("getCatalogData", function () {
var oCatalog = {},
oResult = {},
oLaunchPageAdapter,
oLaunchPageService,
oLogMock = testUtils.createLogMock()
.filterComponent("sap.ushell.services.LaunchPage")
.warning("getCatalogData not implemented in adapter", null,
"sap.ushell.services.LaunchPage");
// part 1: unsupported in adapter
oLaunchPageService = new LaunchPage({
getCatalogId: function (oCatalog0) {
strictEqual(oCatalog0, oCatalog);
return "foo";
}
});
deepEqual(oLaunchPageService.getCatalogData(oCatalog), {id: "foo"});
oLogMock.verify();
// part 2: delegates to adapter
oLaunchPageAdapter = {
getCatalogData: sinon.stub().returns(oResult)
};
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
strictEqual(oLaunchPageService.getCatalogData(oCatalog), oResult);
ok(oLaunchPageAdapter.getCatalogData.calledOnce);
ok(oLaunchPageAdapter.getCatalogData.calledWithExactly(oCatalog));
});
test("test countBookmarks", function () {
var oActualPromise,
oExpectedPromise = (new jQuery.Deferred()).promise(),
oLaunchPageAdapter = {
countBookmarks: sinon.stub().returns(oExpectedPromise)
},
oLaunchPageService;
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
throws(function () {
oLaunchPageService.countBookmarks();
}, /Missing URL/);
throws(function () {
oLaunchPageService.countBookmarks("");
}, /Missing URL/);
throws(function () {
oLaunchPageService.countBookmarks({});
}, /Missing URL/);
ok(oLaunchPageAdapter.countBookmarks.notCalled);
oActualPromise = oLaunchPageService.countBookmarks("###");
strictEqual(oActualPromise, oExpectedPromise);
ok(oLaunchPageAdapter.countBookmarks.calledOnce);
strictEqual(oLaunchPageAdapter.countBookmarks.args[0][0], "###");
});
test("test deleteBookmarks", function () {
var oActualPromise,
oExpectedPromise = (new jQuery.Deferred()).promise(),
oLaunchPageAdapter = {
deleteBookmarks: sinon.stub().returns(oExpectedPromise)
},
oLaunchPageService;
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
throws(function () {
oLaunchPageService.deleteBookmarks();
}, /Missing URL/);
throws(function () {
oLaunchPageService.deleteBookmarks("");
}, /Missing URL/);
throws(function () {
oLaunchPageService.deleteBookmarks({});
}, /Missing URL/);
ok(oLaunchPageAdapter.deleteBookmarks.notCalled);
oActualPromise = oLaunchPageService.deleteBookmarks("###");
strictEqual(oActualPromise, oExpectedPromise);
ok(oLaunchPageAdapter.deleteBookmarks.calledOnce);
strictEqual(oLaunchPageAdapter.deleteBookmarks.args[0][0], "###");
});
test("test updateBookmarks", function () {
var oActualPromise,
oExpectedPromise = (new jQuery.Deferred()).promise(),
oLaunchPageAdapter = {
updateBookmarks: sinon.stub().returns(oExpectedPromise)
},
oLaunchPageService,
oParameters = {
url: "foo"
};
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
throws(function () {
oLaunchPageService.updateBookmarks();
}, /Missing URL/);
throws(function () {
oLaunchPageService.updateBookmarks("");
}, /Missing URL/);
throws(function () {
oLaunchPageService.updateBookmarks({});
}, /Missing URL/);
throws(function () {
oLaunchPageService.updateBookmarks("foo");
}, /Missing parameters/);
throws(function () {
oLaunchPageService.updateBookmarks("foo", true);
}, /Missing parameters/);
ok(oLaunchPageAdapter.updateBookmarks.notCalled);
oActualPromise = oLaunchPageService.updateBookmarks("###", oParameters);
strictEqual(oActualPromise, oExpectedPromise);
ok(oLaunchPageAdapter.updateBookmarks.calledOnce);
strictEqual(oLaunchPageAdapter.updateBookmarks.args[0][0], "###");
strictEqual(oLaunchPageAdapter.updateBookmarks.args[0][1], oParameters);
});
test("Tile actions", function () {
var oTile = {},
aInternalActions,
aExternalActions1,
aExternalActions2,
oLaunchPageAdapter,
oLaunchPageService;
// part 1: no actions
oLaunchPageAdapter = {};
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
deepEqual(oLaunchPageService.getTileActions(oTile), []);
// part 2: internal actions
aInternalActions = [{text: "InternalAction1"}, {text: "InternalAction2"}];
oLaunchPageAdapter = {
getTileActions: sinon.stub().returns(aInternalActions)
};
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
deepEqual(oLaunchPageService.getTileActions(oTile), aInternalActions);
ok(oLaunchPageAdapter.getTileActions.calledWithExactly(oTile));
// part 3: external actions
aExternalActions1 = [{text: "ExternalAction11"}, {text: "ExternalAction12"}];
aExternalActions2 = [{text: "ExternalAction21"}, {text: "ExternalAction22"}];
oLaunchPageAdapter = {};
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.registerTileActionsProvider(sinon.stub().returns(aExternalActions1));
oLaunchPageService.registerTileActionsProvider(sinon.stub().returns(aExternalActions2));
deepEqual(oLaunchPageService.getTileActions(oTile), aExternalActions1.concat(aExternalActions2));
// part 4: internal and external actions
aInternalActions = [{text: "InternalAction1"}, {text: "InternalAction2"}];
oLaunchPageAdapter = {
getTileActions: sinon.stub().returns(aInternalActions)
};
aExternalActions1 = [{text: "ExternalAction11"}, {text: "ExternalAction12"}];
aExternalActions2 = [{text: "ExternalAction21"}, {text: "ExternalAction22"}];
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.registerTileActionsProvider(sinon.stub().returns(aExternalActions1));
oLaunchPageService.registerTileActionsProvider(sinon.stub().returns(aExternalActions2));
deepEqual(oLaunchPageService.getTileActions(oTile), aInternalActions.concat(aExternalActions1.concat(aExternalActions2)));
ok(oLaunchPageAdapter.getTileActions.calledWithExactly(oTile));
});
test("getCatalogTileTargetURL", function () {
var oLaunchPageService,
sTargetUrl,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
// part 1: TargetUrl exist in configuration
sTargetUrl = oLaunchPageService.getCatalogTileTargetURL(oLaunchPageConfig.config.groups[0].tiles[0]);
strictEqual(sTargetUrl, oLaunchPageConfig.config.groups[0].tiles[0].properties.targetURL, "TargetUrl as expected");
// part 2: TargetUrl does not exist in configuration
sTargetUrl = oLaunchPageService.getCatalogTileTargetURL(oLaunchPageConfig.config.groups[0].tiles[1]);
strictEqual(sTargetUrl, null, "TargetUrl default value is null");
});
test("getCatalogTilePreviewTitle", function () {
var oLaunchPageService,
sPreviewTitle,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
// part 1: Title exist in configuration
sPreviewTitle = oLaunchPageService.getCatalogTilePreviewTitle(oLaunchPageConfig.config.groups[0].tiles[0]);
strictEqual(sPreviewTitle, oLaunchPageConfig.config.groups[0].tiles[0].properties.title, "Preview title as expected");
// part 2: Title does not exist in configuration
sPreviewTitle = oLaunchPageService.getCatalogTilePreviewTitle(oLaunchPageConfig.config.groups[0].tiles[1]);
strictEqual(sPreviewTitle, null, "Preview title default value is null");
});
test("getCatalogTilePreviewInfo", function () {
// Arrange
var oLaunchPageService,
sPreviewInfo,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
// Act
sPreviewInfo = oLaunchPageService.getCatalogTilePreviewInfo(oLaunchPageConfig.config.groups[0].tiles[0]);
// Assert
strictEqual(sPreviewInfo, oLaunchPageConfig.config.groups[0].tiles[0].properties.info, "The function getCatalogTilePreviewInfo returns the correct catalog tile preview info.");
});
test("getCatalogTilePreviewSubtitle", function () {
var oLaunchPageService,
sPreviewSubtitle,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
// part 1: Title exist in configuration
sPreviewSubtitle = oLaunchPageService.getCatalogTilePreviewSubtitle(oLaunchPageConfig.config.groups[0].tiles[0]);
strictEqual(sPreviewSubtitle, oLaunchPageConfig.config.groups[0].tiles[0].properties.subtitle, "Preview subtitle as expected");
// part 2: Title does not exist in configuration
sPreviewSubtitle = oLaunchPageService.getCatalogTilePreviewSubtitle(oLaunchPageConfig.config.groups[0].tiles[1]);
strictEqual(sPreviewSubtitle, null, "Preview subtitle default value is null");
});
test("getCatalogTilePreviewIcon", function () {
var oLaunchPageService,
sPreviewIcon,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
// part 1: Title exist in configuration
sPreviewIcon = oLaunchPageService.getCatalogTilePreviewIcon(oLaunchPageConfig.config.groups[0].tiles[0]);
strictEqual(sPreviewIcon, oLaunchPageConfig.config.groups[0].tiles[0].properties.icon, "Preview icon as expected");
// part 2: Title does not exist in configuration
sPreviewIcon = oLaunchPageService.getCatalogTilePreviewIcon(oLaunchPageConfig.config.groups[0].tiles[1]);
strictEqual(sPreviewIcon, null, "Preview icon default value is null");
});
asyncTest("getCatalogWithTranslation", function () {
var oLaunchPageService,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.getCatalogs().done(function (aCatalogs) {
start();
strictEqual(aCatalogs[0].title, "Translated Catalog 1", "Correct catalog [0] title");
strictEqual(aCatalogs[1].title, "Translated Catalog 2", "Correct catalog [1] title");
});
});
asyncTest("getGroupsWithTranslation", function () {
var oLaunchPageService,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
// part 1: unsupported in adapter
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.getGroups().done(function (aGroups) {
start();
strictEqual(aGroups[0].title, "Translated Group 1", "Group translation error for aGroups[0].title");
strictEqual(aGroups[1].title, "Translated Group 2", "Group translation error for aGroups[1].title");
});
});
asyncTest("getGroupsWithFeatureGroup", function () {
var iNumFeaturedGroups,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.getGroups().done(function (aGroups) {
start();
iNumFeaturedGroups = aGroups.filter(function (oGroup) {
return oGroup.contentProvider === "feature";
}).length;
strictEqual(iNumFeaturedGroups, oFixture.output.numberOfFeaturedGroups, "feature group loaded");
});
});
asyncTest("getViewDataWithTranslation", function () {
var oLaunchPageService,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
// part 1: unsupported in adapter
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.getTileView(oLaunchPageConfig.config.groups[0].tiles[0]).done(function (oView) {
start();
strictEqual(oView.getProperty("title"), "Translated Header title", "Translated title check");
strictEqual(oView.getProperty("subtitle"), "Translated Sub Title", "Translated Sub Title");
strictEqual(oView.getProperty("info"), "Translated Info", "Translated Info");
strictEqual(oLaunchPageConfig.config.groups[0].tiles[0].keywords[0], "Translated Keyword", "Translated keywords");
});
});
asyncTest("getViewForComponentTile", function () {
var oLaunchPageService,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
// part 1: unsupported in adapter
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.getTileView(oLaunchPageConfig.config.groups[2].tiles[0]).done(function (oTileUI) {
start();
ok(oTileUI.getMetadata().getName() === "sap.ui.core.ComponentContainer", "Module path registered and Component wrapped with ComponentContainer");
});
});
asyncTest("getViewForViewTileTile", function () {
var oLaunchPageService,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
// part 1: unsupported in adapter
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.getTileView(oLaunchPageConfig.config.groups[2].tiles[1]).done(function (oTileUI) {
start();
ok(oTileUI.getMetadata().getName() === "sap.ui.core.mvc.JSView", "Modelu path registered and View tile retreived");
});
});
asyncTest("getViewForHeaderModeTile", function () {
var oLaunchPageService,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.getTileView(oLaunchPageConfig.config.groups[0].tiles[4]).done(function (oTileUI) {
start();
ok(oTileUI.getProperty("mode") === "HeaderMode", "Tile is in Header Mode");
});
});
asyncTest("getViewForContentModeTile", function () {
var oLaunchPageService,
oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.getTileView(oLaunchPageConfig.config.groups[0].tiles[5]).done(function (oTileUI) {
start();
ok(oTileUI.getProperty("mode") === "ContentMode", "Tile is in Content Mode");
});
});
test("isLinkPersonalizationSupported", function () {
var oTile = {},
oLaunchPageAdapter = {
isLinkPersonalizationSupported: sinon.stub().returns(true)
},
oLaunchPageService;
oLaunchPageService = new LaunchPage({});
strictEqual(oLaunchPageService.isLinkPersonalizationSupported(oTile), false);
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
strictEqual(oLaunchPageService.isLinkPersonalizationSupported(oTile), true);
ok(oLaunchPageAdapter.isLinkPersonalizationSupported.calledOnce);
ok(oLaunchPageAdapter.isLinkPersonalizationSupported.calledWithExactly(oTile));
});
test("getCatalogTileView", function () {
var oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
oLaunchPageService = new LaunchPage(oLaunchPageAdapter),
oTileData = {
namespace: undefined,
path: undefined,
moduleType: undefined,
tileType: "tileTypePart1.tileTypePart2.tileTypePart3",
properties: {
title: "title",
subtitle: "subTitle",
info: "info",
targetURL: "#a-b"
}
},
oView,
oViewConstructor = function (oProps) {
var oViewObject = {
oViewProperties: oProps
};
return oViewObject;
},
oHandleTilePressStub = sinon.stub(oLaunchPageAdapter, "_handleTilePress").returns({}),
oApplyDynamicTileIfoStateStub = sinon.stub(oLaunchPageAdapter, "_applyDynamicTileIfoState").returns({}),
oJQuaryRequireStub = sinon.stub(jQuery.sap, "require"),
oJQuaryGetObjectStub = sinon.stub(jQuery.sap, "getObject").callsFake( function (sObjectPath) {
if (sObjectPath === "tileTypePart1.tileTypePart2.tileTypePart3") {
return oViewConstructor;
}
}),
oRiginalSapUiRequire = sap.ui.require;
sap.ui.require = sinon.spy();
oView = oLaunchPageService.getCatalogTileView(oTileData);
ok(sap.ui.require.called, "sap.ui.require is called");
ok(sap.ui.require.args[sap.ui.require.args.length - 1][0] === "tileTypePart1/tileTypePart2/tileTypePart3", "sap.ui.require called for the view path tileTypePart1/tileTypePart2/tileTypePart3");
ok(oJQuaryGetObjectStub.calledTwice === true, "sap.ui.getObject calledTwice");
ok(oJQuaryGetObjectStub.args[0][0] === "tileTypePart1.tileTypePart2.tileTypePart3", "1st call to sap.ui.getObject for tileTypePart1.tileTypePart2.tileTypePart3");
ok(oJQuaryGetObjectStub.args[1][0] === "tileTypePart1.tileTypePart2.tileTypePart3", "2nd call to sap.ui.getObject for tileTypePart1.tileTypePart2.tileTypePart3");
ok(oHandleTilePressStub.calledOnce === true, "_handleTilePressStub called once");
ok(oApplyDynamicTileIfoStateStub.calledOnce === true, "_applyDynamicTileIfoState called once");
ok(oView.oViewProperties.title === "title", "Returned view title is correct");
sap.ui.require = oRiginalSapUiRequire;
oJQuaryRequireStub.restore();
oJQuaryGetObjectStub.restore();
oHandleTilePressStub.restore();
oApplyDynamicTileIfoStateStub.restore();
});
asyncTest("getCatalogTileViewControl", function () {
var oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
oLaunchPageService = new LaunchPage(oLaunchPageAdapter),
oTileData = {
namespace: undefined,
path: undefined,
moduleType: undefined,
tileType: "tileTypePart1.tileTypePart2.tileTypePart3",
properties: {
title: "title",
subtitle: "subTitle",
info: "info",
targetURL: "#a-b"
}
},
oViewConstructor = function (oProps) {
var oViewObject = {
oViewProperties: oProps
};
return oViewObject;
},
oOrigRequire = sap.ui.require,
oGetImageContentStub = sinon.stub(oLaunchPageAdapter, "_getImageContent").returns({
addStyleClass: function () {}
}),
oRequireStub = sinon.stub(sap.ui, "require").callsFake( function (aRequirePath, fCallback) {
fCallback(oViewConstructor);
}),
oHandleTilePressStub = sinon.stub(oLaunchPageAdapter, "_handleTilePress").returns({}),
oApplyDynamicTileIfoState = sinon.stub(oLaunchPageAdapter, "_applyDynamicTileIfoState").returns({});
oLaunchPageService.getCatalogTileViewControl(oTileData).done(function (oView) {
start();
ok(oRequireStub.callCount === 1, "sap.ui.require called");
ok(oRequireStub.args[0][0][0] === "tileTypePart1/tileTypePart2/tileTypePart3", "sap.ui.require called for tileTypePart1/tileTypePart2/tileTypePart3");
ok(oHandleTilePressStub.calledOnce === true, "_handleTilePressStub called once");
ok(oApplyDynamicTileIfoState.calledOnce === true, "_applyDynamicTileIfoState called once");
ok(oView.oViewProperties.title === "title", "Returned view title is correct");
sap.ui.require = oOrigRequire;
oGetImageContentStub.restore();
oHandleTilePressStub.restore();
oApplyDynamicTileIfoState.restore();
});
});
test("getCatalogTileViewRedirect", function () {
var oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
oLaunchPageService = new LaunchPage(oLaunchPageAdapter),
oGetCatalogTileViewStub;
oLaunchPageAdapter.getCatalogTileViewControl = undefined;
oGetCatalogTileViewStub = sinon.stub(oLaunchPageAdapter, "getCatalogTileView").returns({text: "viewText"});
oLaunchPageService.getCatalogTileViewControl().done(function (obj) {
ok(oLaunchPageAdapter.getCatalogTileView.calledOnce === true, "When adapter function getCatalogTileViewControl does not exist - getCatalogTileView is called");
ok(obj.text === "viewText", "Correct returned object");
oGetCatalogTileViewStub.restore();
});
});
});
asyncTest("getGroupsForBookmarks when part of the groups are locked or not visable", function () {
var oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.getGroupsForBookmarks().done(function (aGroups) {
start();
strictEqual(aGroups.length, 3, "groups were filtered correctly");
strictEqual(aGroups[0].title, "My Home", "title was changed correctly");
});
});
module("getGroups", function () {
asyncTest("getGroups with pages enabled should return a promise resolving to an empty array", function() {
var oConfigStub = sinon.stub(Config, "last");
oConfigStub.withArgs("/core/spaces/enabled").returns(true);
var oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
oLaunchPageService.getGroups().done(function (aGroups) {
strictEqual(aGroups.length, 0, "an empty array is returned");
start();
});
});
});
});