How to use launch method in Puppeteer

Best JavaScript code snippet using puppeteer

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

launches.model.js

Source: launches.model.js Github

copy
1const axios = require('axios');
2// Linking our mongodb launches collection
3const launchesDatabase = require('./launches.mongo');
4const planets = require('./planets.mongo');
5
6// Default flight number in case our getLatestLaunch function has no launches to reference
7const DEFAULT_FLIGHT_NUMBER = 100;
8
9// SpaceX API url
10const SPACEX_API_URL = "https://api.spacexdata.com/v4/launches/query";
11
12// Saving SpaceX launches to our database
13async function populateLaunches() {
14    console.log("Downloading launches data...");
15    const response = await axios.post(SPACEX_API_URL, {
16        query: {},
17        options: {
18            pagination: false,
19            populate: [
20                {
21                    path: 'rocket',
22                    select: {
23                        name: 1
24                    }
25
26                },
27                {
28                    path: 'payloads',
29                    select: {
30                        'customers': 1
31                    }
32                }
33            ]
34        }
35    });
36
37    if (response.status != 200) {
38        console.log('Problem downloading launch data');
39        throw new Error('Launch data download failed');
40    }
41    // Response from our axios query for launch data, which axios stores in a docs array in the response.data   
42    const launchDocs = response.data.docs
43    // Looping over the launch data to make a launch object to save in our database
44    for (const launchDoc of launchDocs) {
45        // 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
46        const payloads = launchDoc['payloads'];
47        // 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
48        const customers = payloads.flatMap((payload) => {
49            return payload['customers'];
50        });
51
52        const launch = {
53            flightNumber: launchDoc['flight_number'],
54            mission: launchDoc['name'],
55            rocket: launchDoc['rocket']['name'],
56            launchDate: launchDoc['date_local'],
57            upcoming: launchDoc['upcoming'],
58            success: launchDoc['success'],
59            customers
60        }
61        console.log(`${launch.flightNumber}, ${launch.mission}`);
62        // Populate launches collection
63        await saveLaunch(launch);
64    }
65}
66// Loading all the SpaceX launch data we need with axios
67async function loadLaunchesData() {
68    // Checking if the data has already been loaded
69    const firstLaunch = await findLaunch({
70        flightNumber: 1,
71        rocket: 'Falcon 1',
72        mission: 'FalconSat'
73    });
74    if (firstLaunch) {
75        console.log('Launch data already loaded');
76    } else {
77        await populateLaunches();
78    }
79}
80
81// Function to use to only add launches not in our database already
82async function findLaunch(filter) {
83    return await launchesDatabase.findOne(filter);
84}
85// See if a launch exists within our database
86async function existsLaunchWithId(launchId) {
87    return await findLaunch({
88        flightNumber: launchId
89    });
90}
91
92// Get our latest flight number from the database using a filter that finds the highest flight number value
93async function getLatestFlightNumber() {
94    const latestLaunch = await launchesDatabase
95        .findOne()
96        .sort('-flightNumber');
97
98    if (!latestLaunch) {
99        return DEFAULT_FLIGHT_NUMBER;
100    }
101
102    return latestLaunch.flightNumber;
103}
104
105// GET all launches
106async function getAllLaunches(skip, limit) {
107    return await launchesDatabase
108    .find({}, { '_id': 0, '__v': 0})
109    .sort({ flightNumber: 1 })
110    .skip(skip)
111    .limit(limit);
112}
113
114// Saving launches to mongodb
115async function saveLaunch(launch) {
116    // Saving a doocument with the newly passed in launch object, or updating it if it already exists by flight number
117    try {
118        await launchesDatabase.findOneAndUpdate({
119            flightNumber: launch.flightNumber,
120        }, launch, {
121            upsert: true
122        })} catch(err) {
123                return console.error(`Could not save launch ${err}`); 
124    }
125}
126
127// Adding a document containing a new launch to mongodb
128async function scheduleNewLaunch(launch) {
129    // Validating the planet exists, so we do not add launches to planets that do not exist in our database
130    const planet = await planets.findOne({
131        keplerName: launch.target
132    });
133
134    if (!planet) {
135        throw new Error('No matching planet was found');
136    }
137
138    const newFlightNumber = await getLatestFlightNumber() + 1;
139
140    const newLaunch = Object.assign(launch, {
141        success: true,
142        upcoming: true,
143        customers: ['ZTM', 'NASA'],
144        flightNumber: newFlightNumber
145    });
146
147    await saveLaunch(newLaunch);
148}
149
150// Rather than deleting aborted launches outright, update them to show they are not successful and are no longer upcoming
151async function abortLaunchById(launchId) {
152    const aborted = await launchesDatabase.updateOne({
153        flightNumber: launchId
154    }, {
155        upcoming: false,
156        success: false
157    });
158    /* 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
159    const aborted = await abortLaunchById(launchId);
160    return res.status(200).json(aborted); */
161    return aborted.modifiedCount === 1;
162}
163
164module.exports = {
165    loadLaunchesData,
166    existsLaunchWithId,
167    getAllLaunches,
168    scheduleNewLaunch,
169    abortLaunchById
170};
Full Screen

launch.js

Source: launch.js Github

copy
1const { RESTDataSource } = require('apollo-datasource-rest');
2
3class LaunchAPI extends RESTDataSource {
4  constructor() {
5    super();
6    this.baseURL = 'https://api.spacexdata.com/v2/';
7  }
8
9  // Create a rocket object although it is based on a launch
10  rocketReducer(launch) {
11    let launchFailureDetails = null
12    if(launch.launch_failure_details) {
13      launchFailureDetails = launch.launch_failure_details.reason
14    }
15    return {
16      id: launch.rocket.rocket_id,
17      name: launch.rocket.rocket_name,
18      mission: {
19        name: launch.mission_name,
20        launchDateLocal: launch.launch_date_local,
21        launchSuccess: launch.launch_success,
22        launchFailureDetails: launchFailureDetails,
23        missionPatchSmall:launch.links.mission_patch_small
24      },
25      site: {
26        name: launch.launch_site.site_name
27      }
28    }
29  };
30
31  // Group launches by rocket id
32  groupRockets(launches) {
33    const launchesByRocket = new Map();
34    let rocketId, rocketLaunches;
35    launches.forEach((launch) => {
36      rocketId = launch.rocket.rocket_id;
37      rocketLaunches = launchesByRocket.get(rocketId);
38      if (!rocketLaunches) {
39        launchesByRocket.set(rocketId, launch);
40      } else {
41        // To simplify the project, I'll use only one launch per rocket
42        // rocketLaunches.push(launch)
43      }
44    })
45    return launchesByRocket;
46  }
47
48  // leaving this inside the class to make the class easier to test
49  launchReducer(launch) {
50    return {
51      id: launch.flight_number || 0,
52      cursor: `${launch.launch_date_local}`,
53      site: launch.launch_site && launch.launch_site.site_name,
54      mission: {
55        name: launch.mission_name,
56        missionPatchSmall: launch.links.mission_patch_small,
57        missionPatchLarge: launch.links.mission_patch,
58      },
59      rocket: {
60        id: launch.rocket.rocket_id,
61        name: launch.rocket.rocket_name,
62        type: launch.rocket.rocket_type,
63        
64      },
65    };
66  }
67
68  async getAllRockets() {
69    const response = await this.get('launches');
70
71    if (Array.isArray(response)) {
72      const launchesPerRocket = Array.from(this.groupRockets(response).values());
73      const result = launchesPerRocket.map(launch => this.rocketReducer(launch))
74
75      return result
76    } else {
77      return []
78    }
79  }
80
81  async getAllLaunches() {
82    const response = await this.get('launches');
83
84    // transform the raw launches to a more friendly
85    return Array.isArray(response)
86      ? response.map(launch => this.launchReducer(launch)) : [];
87  }
88
89  async getLaunchById({ launchId }) {
90    const res = await this.get('launches', { flight_number: launchId });
91    return this.launchReducer(res[0]);
92  }
93
94  async getLaunchesByIds({ launchIds }) {
95    return Promise.all(
96      launchIds.map(launchId => this.getLaunchById({ launchId })),
97    );
98  }
99}
100
101module.exports = LaunchAPI;
102
Full Screen

core_node_controller

Source: core_node_controller Github

copy
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4################################################################################
5# Copyright 2018 ROBOTIS CO., LTD.
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11#     http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18################################################################################
19
20# Authors: Leon Jung, [AuTURBO] Kihoon Kim (https://github.com/auturbo), Gilbert
21
22import rospy, roslaunch
23import numpy as np
24import subprocess
25import os
26import sys
27from enum import Enum
28from std_msgs.msg import UInt8
29 
30class CoreNodeController():
31    def __init__(self):
32        self.ros_package_path = os.path.dirname(os.path.realpath(__file__))
33        self.ros_package_path = self.ros_package_path.replace('turtlebot3_autorace_core/nodes', '')
34
35        self.sub_mode_control = rospy.Subscriber('/core/decided_mode', UInt8, self.cbReceiveMode, queue_size=1)
36
37        self.CurrentMode = Enum('CurrentMode', 'idle lane_following traffic_light parking_lot level_crossing tunnel')
38
39        # subscribes : status returned
40        self.sub_parking_lot_stamped = rospy.Subscriber('/detect/parking_lot_stamped', UInt8, self.cbParkingLotStamped, queue_size=1)
41        self.sub_level_crossing_stamped = rospy.Subscriber('/detect/level_crossing_stamped', UInt8, self.cbLevelCrossingStamped, queue_size=1)
42        self.sub_tunnel_stamped = rospy.Subscriber('/detect/tunnel_stamped', UInt8, self.cbTunnelStamped, queue_size=1)
43
44        # publishes orders
45        self.pub_traffic_light_order = rospy.Publisher('/detect/traffic_light_order', UInt8, queue_size=1)
46        self.pub_parking_lot_order = rospy.Publisher('/detect/parking_lot_order', UInt8, queue_size=1)
47        self.pub_level_crossing_order = rospy.Publisher('/detect/level_crossing_order', UInt8, queue_size=1)
48        self.pub_tunnel_order = rospy.Publisher('/detect/tunnel_order', UInt8, queue_size=1)
49
50        self.pub_mode_return = rospy.Publisher('/core/returned_mode', UInt8, queue_size=1)
51
52        self.StepOfParkingLot = Enum('StepOfParkingLot', 'searching_parking_sign searching_parking_point_line searching_nonreserved_parking_area parking')
53        self.StepOfLevelCrossing = Enum('StepOfLevelCrossing', 'searching_stop_sign searching_level watching_level stop pass_level')
54        self.StepOfTunnel = Enum('StepOfTunnel', 'searching_tunnel_sign go_in_to_tunnel navigation go_out_from_tunnel exit')
55
56        self.current_step_parking_lot = self.StepOfParkingLot.searching_parking_sign.value
57        self.current_step_level_crossing = self.StepOfLevelCrossing.searching_stop_sign.value
58        self.current_step_tunnel = self.StepOfTunnel.searching_tunnel_sign.value
59
60        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')
61
62        self.uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)
63        
64        self.launch_camera_launched = False
65        self.launch_detect_sign_launched = False
66        self.launch_detect_lane_launched = False    
67        self.launch_control_lane_launched = False
68        self.launch_detect_parking_launched = False
69        self.launch_control_parking_launched = False
70        self.launch_detect_level_launched = False
71        self.launch_detect_traffic_light_launched = False
72        self.launch_detect_tunnel_launched = False
73        self.launch_control_tunnel_launched = False
74
75        self.current_mode = self.CurrentMode.idle.value
76
77        self.is_triggered = False
78
79        loop_rate = rospy.Rate(10) # 10hz
80        while not rospy.is_shutdown():
81            if self.is_triggered == True:
82                self.fnControlNode()
83            
84            loop_rate.sleep()
85
86    def cbReceiveMode(self, mode_msg):
87        rospy.loginfo("starts the progress with %d", mode_msg.data)
88        
89        self.current_mode = mode_msg.data
90        self.is_triggered = True
91
92    # Which step is in Parking Lot
93    def cbParkingLotStamped(self, parking_lot_msg):
94        rospy.loginfo("ParkingLot Step changed from %d", self.current_step_parking_lot)
95
96        self.current_step_parking_lot = parking_lot_msg.data
97
98        rospy.loginfo("into %d", self.current_step_parking_lot)
99
100        if self.current_step_parking_lot == self.StepOfParkingLot.parking.value:
101            self.current_mode = self.CurrentMode.lane_following.value
102            msg_mode_return = UInt8()
103            msg_mode_return.data = self.current_mode
104            self.current_step_parking_lot = self.StepOfParkingLot.searching_parking_sign.value
105
106            rospy.loginfo("pub_mode_return")
107            self.pub_mode_return.publish(msg_mode_return)
108
109        self.is_triggered = True
110
111    # Which step is in Level Crossing  
112    def cbLevelCrossingStamped(self, level_crossing_msg):
113        rospy.loginfo("LevelCrossing Step changed from %d", self.current_step_level_crossing)
114
115        self.current_step_level_crossing = level_crossing_msg.data
116
117        rospy.loginfo("into %d", self.current_step_level_crossing)
118
119        if self.current_step_level_crossing == self.StepOfLevelCrossing.pass_level.value:
120            self.current_mode = self.CurrentMode.level_crossing.value
121            msg_mode_return = UInt8()
122            msg_mode_return.data = self.current_mode
123            self.pub_mode_return.publish(msg_mode_return)
124
125        self.is_triggered = True
126
127    # Which step is in Tunnel
128    def cbTunnelStamped(self, tunnel_msg):
129        rospy.loginfo("Tunnel Step changed from %d", self.current_step_tunnel)
130
131        self.current_step_tunnel = tunnel_msg.data
132
133        rospy.loginfo("into %d", self.current_step_tunnel)
134
135        if self.current_step_tunnel == self.StepOfTunnel.searching_tunnel_sign.value:
136            self.current_mode = self.CurrentMode.tunnel.value
137            msg_mode_return = UInt8()
138            msg_mode_return.data = self.current_mode
139            self.pub_mode_return.publish(msg_mode_return)
140
141        self.is_triggered = True
142
143    def fnControlNode(self):
144        # lane_following
145        if self.current_mode == self.CurrentMode.lane_following.value:
146            rospy.loginfo("New trigger for lane_following")
147
148            self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
149
150            self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
151            self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
152            self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
153            self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
154            self.fnLaunch(self.Launcher.launch_detect_level.value, False)
155            self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
156
157            self.fnLaunch(self.Launcher.launch_control_lane.value, True)
158            self.fnLaunch(self.Launcher.launch_control_parking.value, False)
159            self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
160              
161        # traffic_light
162        elif self.current_mode == self.CurrentMode.traffic_light.value:
163            rospy.loginfo("New trigger for traffic_light")
164            msg_pub_traffic_light_order = UInt8()
165
166            if self.current_step_traffic_light == self.StepOfTrafficLight.searching_traffic_light.value:
167                rospy.loginfo("Current step : searching_traffic_light")
168                rospy.loginfo("Go to next step : in_traffic_light")
169
170                msg_pub_traffic_light_order.data = self.StepOfTrafficLight.in_traffic_light.value
171
172                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
173                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
174                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
175                self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
176                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
177                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
178
179                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
180                self.fnLaunch(self.Launcher.launch_control_parking.value, False)
181                self.fnLaunch(self.Launcher.launch_control_level.value, False)
182
183            elif self.current_step_traffic_light == self.StepOfTrafficLight.in_traffic_light.value:
184                rospy.loginfo("Current step : in_traffic_light")
185                rospy.loginfo("Go to next step : pass_traffic_light")
186
187                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
188                self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
189                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
190                self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
191                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
192                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
193
194                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
195                self.fnLaunch(self.Launcher.launch_control_parking.value, False)
196                self.fnLaunch(self.Launcher.launch_control_level.value, False)
197
198            rospy.sleep(2)
199
200            self.pub_traffic_light_order.publish(msg_pub_traffic_light_order)
201
202        # parking_lot
203        elif self.current_mode == self.CurrentMode.parking_lot.value:
204            rospy.loginfo("New trigger for parking_lot")
205            msg_pub_parking_lot_order = UInt8()
206
207            if self.current_step_parking_lot == self.StepOfParkingLot.searching_parking_sign.value:
208                rospy.loginfo("Current step : searching_parking_sign")
209                rospy.loginfo("Go to next step : searching_parking_point_line")
210
211                msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_parking_point_line.value
212
213                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
214                self.fnLaunch(self.Launcher.launch_control_parking.value, False)
215
216                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
217                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
218                self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
219                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
220                                   
221            elif self.current_step_parking_lot == self.StepOfParkingLot.searching_parking_point_line.value:
222                rospy.loginfo("Current step : searching_parking_point_line")
223                rospy.loginfo("Go to next step : searching_nonreserved_parking_area")
224
225                msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_nonreserved_parking_area.value
226
227                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
228                self.fnLaunch(self.Launcher.launch_control_parking.value, True)
229
230                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
231                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
232                self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
233                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
234
235            elif self.current_step_parking_lot == self.StepOfParkingLot.searching_nonreserved_parking_area.value:
236                rospy.loginfo("Current step : searching_nonreserved_parking_area")
237                rospy.loginfo("Go to next step : parking")
238
239                msg_pub_parking_lot_order.data = self.StepOfParkingLot.parking.value
240
241                self.fnLaunch(self.Launcher.launch_control_lane.value, False)
242                self.fnLaunch(self.Launcher.launch_control_parking.value, True)
243                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
244                self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
245                self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
246                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
247
248            elif self.current_step_parking_lot == self.StepOfParkingLot.parking.value:
249                rospy.loginfo("Current step : parking")
250                rospy.loginfo("Go to next step : searching_parking_sign")
251
252                msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_parking_sign.value
253
254                self.fnLaunch(self.Launcher.launch_control_parking.value, False)
255                self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
256                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
257                self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
258                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
259                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
260
261            rospy.sleep(2)
262
263            self.pub_parking_lot_order.publish(msg_pub_parking_lot_order)
264
265        # level_crossing
266        elif self.current_mode == self.CurrentMode.level_crossing.value:
267            rospy.loginfo("New trigger for level_crossing")
268            msg_pub_level_crossing_order = UInt8()
269
270            if self.current_step_level_crossing == self.StepOfLevelCrossing.searching_stop_sign.value:
271                rospy.loginfo("Current step : searching_stop_sign")
272                rospy.loginfo("Go to next step : searching_level")
273
274                msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.searching_level.value
275
276                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
277                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
278                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
279                self.fnLaunch(self.Launcher.launch_detect_level.value, True)
280                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
281                                   
282            elif self.current_step_level_crossing == self.StepOfLevelCrossing.searching_level.value:
283                rospy.loginfo("Current step : searching_level")
284                rospy.loginfo("Go to next step : watching_level")
285
286                msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.watching_level.value
287
288                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
289                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
290                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
291                self.fnLaunch(self.Launcher.launch_detect_level.value, True)
292                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
293
294            elif self.current_step_level_crossing == self.StepOfLevelCrossing.watching_level.value:
295                rospy.loginfo("Current step : watching_level")
296                rospy.loginfo("Go to next step : stop")
297
298                msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.stop.value
299
300                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
301                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
302                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
303                self.fnLaunch(self.Launcher.launch_detect_level.value, True)
304                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
305
306            elif self.current_step_level_crossing == self.StepOfLevelCrossing.stop.value:
307                rospy.loginfo("Current step : stop")
308                rospy.loginfo("Go to next step : pass_level")
309
310                msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.pass_level.value
311
312                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
313                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
314                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
315                self.fnLaunch(self.Launcher.launch_detect_level.value, True)
316                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
317
318            elif self.current_step_level_crossing == self.StepOfLevelCrossing.pass_level.value:
319                rospy.loginfo("Current step : pass_level")
320                rospy.loginfo("Go to next step : searching_stop_sign")
321
322                msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.searching_stop_sign.value
323
324                self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
325                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
326                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
327                self.fnLaunch(self.Launcher.launch_detect_level.value, True)
328                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
329
330            rospy.sleep(2)
331
332            self.pub_level_crossing_order.publish(msg_pub_level_crossing_order)
333
334        # tunnel
335        elif self.current_mode == self.CurrentMode.tunnel.value:
336            rospy.loginfo("New trigger for tunnel")
337            msg_pub_tunnel_order = UInt8()
338
339            if self.current_step_tunnel == self.StepOfTunnel.searching_tunnel_sign.value:
340                rospy.loginfo("Current step : searching_tunnel_sign")
341                rospy.loginfo("Go to next step : go_in_to_tunnel")
342
343                msg_pub_tunnel_order.data = self.StepOfTunnel.go_in_to_tunnel.value
344
345                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
346                self.fnLaunch(self.Launcher.launch_control_lane.value, False)
347                self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, False)
348                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
349                self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
350                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
351                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
352
353                self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
354                                   
355            elif self.current_step_tunnel == self.StepOfTunnel.go_in_to_tunnel.value:
356                rospy.loginfo("Current step : go_in_to_tunnel")
357                rospy.loginfo("Go to next step : navigation")
358
359                msg_pub_tunnel_order.data = self.StepOfTunnel.navigation.value
360
361                self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, False)
362                self.fnLaunch(self.Launcher.launch_control_lane.value, False)
363                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
364                self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
365                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
366                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
367                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
368
369                self.fnLaunch(self.Launcher.launch_control_tunnel.value, True)
370
371            elif self.current_step_tunnel == self.StepOfTunnel.navigation.value:
372                rospy.loginfo("Current step : navigation")
373                rospy.loginfo("Go to next step : go_out_from_tunnel")
374
375                msg_pub_tunnel_order.data = self.StepOfTunnel.go_out_from_tunnel.value
376
377                self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
378                self.fnLaunch(self.Launcher.launch_control_lane.value, False)
379                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
380                self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
381                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
382                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
383                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
384
385                self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
386
387            elif self.current_step_tunnel == self.StepOfTunnel.go_out_from_tunnel.value:
388                rospy.loginfo("Current step : go_out_from_tunnel")
389                rospy.loginfo("Go to next step : exit")
390
391                msg_pub_tunnel_order.data = self.StepOfTunnel.exit.value
392
393                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
394                self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
395                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
396                self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
397                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
398                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
399                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
400
401                self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
402
403            elif self.current_step_tunnel == self.StepOfTunnel.exit.value:
404                rospy.loginfo("Current step : exit")
405                rospy.loginfo("Go to next step : searching_tunnel_sign")
406
407                msg_pub_tunnel_order.data = self.StepOfTunnel.searching_tunnel_sign.value
408
409                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
410                self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
411                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
412                self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
413                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
414                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
415                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
416
417                self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
418                
419            rospy.sleep(2)
420
421            self.pub_tunnel_order.publish(msg_pub_tunnel_order)
422
423        self.is_triggered = False
424
425    def fnLaunch(self, launch_num, is_start):
426        if launch_num == self.Launcher.launch_camera_ex_calib.value:
427            if is_start == True:
428                if self.launch_camera_launched == False:
429                    self.launch_camera = roslaunch.scriptapi.ROSLaunch()
430                    self.launch_camera = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_camera/launch/turtlebot3_autorace_extrinsic_camera_calibration.launch"])
431                    self.launch_camera_launched = True
432                    self.launch_camera.start()
433                else:
434                    pass
435            else:
436                if self.launch_camera_launched == True:
437                    self.launch_camera_launched = False
438                    self.launch_camera.shutdown()
439                else:
440                    pass
441        elif launch_num == self.Launcher.launch_detect_sign.value:
442            if is_start == True:
443                if self.launch_detect_sign_launched == False:
444                    self.launch_detect_sign = roslaunch.scriptapi.ROSLaunch()
445                    self.launch_detect_sign = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_sign.launch"])
446                    self.launch_detect_sign_launched = True
447                    self.launch_detect_sign.start()
448                else:
449                    pass
450            else:
451                if self.launch_detect_sign_launched == True:
452                    self.launch_detect_sign_launched = False
453                    self.launch_detect_sign.shutdown()
454                else:
455                    pass                
456        elif launch_num == self.Launcher.launch_detect_lane.value:
457            if is_start == True:
458                if self.launch_detect_lane_launched == False:
459                    self.launch_detect_lane = roslaunch.scriptapi.ROSLaunch()
460                    self.launch_detect_lane = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_lane.launch"])
461                    self.launch_detect_lane_launched = True
462                    self.launch_detect_lane.start()
463                else:
464                    pass
465            else:
466                if self.launch_detect_lane_launched == True:
467                    self.launch_detect_lane_launched = False
468                    self.launch_detect_lane.shutdown()
469                else:
470                    pass                  
471        elif launch_num == self.Launcher.launch_control_lane.value:
472            if is_start == True:
473                if self.launch_control_lane_launched == False:
474                    self.launch_control_lane = roslaunch.scriptapi.ROSLaunch()
475                    self.launch_control_lane = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_lane.launch"])
476                    self.launch_control_lane_launched = True
477                    self.launch_control_lane.start()
478                else:
479                    pass
480            else:
481                if self.launch_control_lane_launched == True:
482                    self.launch_control_lane_launched = False
483                    self.launch_control_lane.shutdown()
484                else:
485                    pass                  
486        elif launch_num == self.Launcher.launch_detect_parking.value:
487            if is_start == True:
488                if self.launch_detect_parking_launched == False:
489                    self.launch_detect_parking = roslaunch.scriptapi.ROSLaunch()
490                    self.launch_detect_parking = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_parking.launch"])
491                    self.launch_detect_parking_launched = True
492                    self.launch_detect_parking.start()
493                else:
494                    pass
495            else:
496                if self.launch_detect_parking_launched == True:
497                    self.launch_detect_parking_launched = False
498                    self.launch_detect_parking.shutdown()
499                else:
500                    pass                  
501        elif launch_num == self.Launcher.launch_control_parking.value:
502            if is_start == True:
503                if self.launch_control_parking_launched == False:
504                    self.launch_control_parking = roslaunch.scriptapi.ROSLaunch()
505                    self.launch_control_parking = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_parking.launch"])     
506                    self.launch_control_parking_launched = True
507                    self.launch_control_parking.start()
508                else:
509                    pass
510            else:
511                if self.launch_control_parking_launched == True:
512                    self.launch_control_parking_launched = False
513                    self.launch_control_parking.shutdown()
514                else:
515                    pass
516        elif launch_num == self.Launcher.launch_detect_level.value:
517            if is_start == True:
518                if self.launch_detect_level_launched == False:
519                    self.launch_detect_level = roslaunch.scriptapi.ROSLaunch()
520                    self.launch_detect_level = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_level.launch"])     
521                    self.launch_detect_level_launched = True
522                    self.launch_detect_level.start()
523                else:
524                    pass
525            else:
526                if self.launch_detect_level_launched == True:
527                    self.launch_detect_level_launched = False
528                    self.launch_detect_level.shutdown()
529                else:
530                    pass                  
531        elif launch_num == self.Launcher.launch_detect_traffic_light.value:
532            if is_start == True:
533                if self.launch_detect_traffic_light_launched == False:
534                    self.launch_detect_traffic_light = roslaunch.scriptapi.ROSLaunch()
535                    self.launch_detect_traffic_light = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_traffic_light.launch"])     
536                    self.launch_detect_traffic_light_launched = True
537                    self.launch_detect_traffic_light.start()
538                else:
539                    pass
540            else:
541                if self.launch_detect_traffic_light_launched == True:
542                    self.launch_detect_traffic_light_launched = False
543                    self.launch_detect_traffic_light.shutdown()
544                else:
545                    pass    
546                    
547        elif launch_num == self.Launcher.launch_detect_tunnel.value:
548            if is_start == True:
549                if self.launch_detect_tunnel_launched == False:
550                    self.launch_detect_tunnel = roslaunch.scriptapi.ROSLaunch()
551                    self.launch_detect_tunnel = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_tunnel.launch"])     
552                    self.launch_detect_tunnel_launched = True
553                    self.launch_detect_tunnel.start()
554                else:
555                    pass
556            else:
557                if self.launch_detect_tunnel_launched == True:
558                    self.launch_detect_tunnel_launched = False
559                    self.launch_detect_tunnel.shutdown()
560                else:
561                    pass    
562        elif launch_num == self.Launcher.launch_control_tunnel.value:
563            if is_start == True:
564                if self.launch_control_tunnel_launched == False:
565                    self.launch_control_tunnel = roslaunch.scriptapi.ROSLaunch()
566                    self.launch_control_tunnel = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_tunnel.launch"])     
567                    self.launch_control_tunnel_launched = True
568                    self.launch_control_tunnel.start()
569                else:
570                    pass
571            else:
572                if self.launch_control_tunnel_launched == True:
573                    self.launch_control_tunnel_launched = False
574                    self.launch_control_tunnel.shutdown()
575                else:
576                    pass
577
578    def main(self):
579        rospy.spin()
580
581if __name__ == '__main__':
582    rospy.init_node('core_node_controller')
583    node = CoreNodeController()
584    node.main()
585
Full Screen

core_node_controller.stamp

Source: core_node_controller.stamp Github

copy
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4################################################################################
5# Copyright 2018 ROBOTIS CO., LTD.
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11#     http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18################################################################################
19
20# Authors: Leon Jung, [AuTURBO] Kihoon Kim (https://github.com/auturbo), Gilbert
21
22import rospy, roslaunch
23import numpy as np
24import subprocess
25import os
26import sys
27from enum import Enum
28from std_msgs.msg import UInt8
29 
30class CoreNodeController():
31    def __init__(self):
32        self.ros_package_path = os.path.dirname(os.path.realpath(__file__))
33        self.ros_package_path = self.ros_package_path.replace('turtlebot3_autorace_core/nodes', '')
34
35        self.sub_mode_control = rospy.Subscriber('/core/decided_mode', UInt8, self.cbReceiveMode, queue_size=1)
36
37        self.CurrentMode = Enum('CurrentMode', 'idle lane_following traffic_light parking_lot level_crossing tunnel')
38
39        # subscribes : status returned
40        self.sub_parking_lot_stamped = rospy.Subscriber('/detect/parking_lot_stamped', UInt8, self.cbParkingLotStamped, queue_size=1)
41        self.sub_level_crossing_stamped = rospy.Subscriber('/detect/level_crossing_stamped', UInt8, self.cbLevelCrossingStamped, queue_size=1)
42        self.sub_tunnel_stamped = rospy.Subscriber('/detect/tunnel_stamped', UInt8, self.cbTunnelStamped, queue_size=1)
43
44        # publishes orders
45        self.pub_traffic_light_order = rospy.Publisher('/detect/traffic_light_order', UInt8, queue_size=1)
46        self.pub_parking_lot_order = rospy.Publisher('/detect/parking_lot_order', UInt8, queue_size=1)
47        self.pub_level_crossing_order = rospy.Publisher('/detect/level_crossing_order', UInt8, queue_size=1)
48        self.pub_tunnel_order = rospy.Publisher('/detect/tunnel_order', UInt8, queue_size=1)
49
50        self.pub_mode_return = rospy.Publisher('/core/returned_mode', UInt8, queue_size=1)
51
52        self.StepOfParkingLot = Enum('StepOfParkingLot', 'searching_parking_sign searching_parking_point_line searching_nonreserved_parking_area parking')
53        self.StepOfLevelCrossing = Enum('StepOfLevelCrossing', 'searching_stop_sign searching_level watching_level stop pass_level')
54        self.StepOfTunnel = Enum('StepOfTunnel', 'searching_tunnel_sign go_in_to_tunnel navigation go_out_from_tunnel exit')
55
56        self.current_step_parking_lot = self.StepOfParkingLot.searching_parking_sign.value
57        self.current_step_level_crossing = self.StepOfLevelCrossing.searching_stop_sign.value
58        self.current_step_tunnel = self.StepOfTunnel.searching_tunnel_sign.value
59
60        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')
61
62        self.uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)
63        
64        self.launch_camera_launched = False
65        self.launch_detect_sign_launched = False
66        self.launch_detect_lane_launched = False    
67        self.launch_control_lane_launched = False
68        self.launch_detect_parking_launched = False
69        self.launch_control_parking_launched = False
70        self.launch_detect_level_launched = False
71        self.launch_detect_traffic_light_launched = False
72        self.launch_detect_tunnel_launched = False
73        self.launch_control_tunnel_launched = False
74
75        self.current_mode = self.CurrentMode.idle.value
76
77        self.is_triggered = False
78
79        loop_rate = rospy.Rate(10) # 10hz
80        while not rospy.is_shutdown():
81            if self.is_triggered == True:
82                self.fnControlNode()
83            
84            loop_rate.sleep()
85
86    def cbReceiveMode(self, mode_msg):
87        rospy.loginfo("starts the progress with %d", mode_msg.data)
88        
89        self.current_mode = mode_msg.data
90        self.is_triggered = True
91
92    # Which step is in Parking Lot
93    def cbParkingLotStamped(self, parking_lot_msg):
94        rospy.loginfo("ParkingLot Step changed from %d", self.current_step_parking_lot)
95
96        self.current_step_parking_lot = parking_lot_msg.data
97
98        rospy.loginfo("into %d", self.current_step_parking_lot)
99
100        if self.current_step_parking_lot == self.StepOfParkingLot.parking.value:
101            self.current_mode = self.CurrentMode.lane_following.value
102            msg_mode_return = UInt8()
103            msg_mode_return.data = self.current_mode
104            self.current_step_parking_lot = self.StepOfParkingLot.searching_parking_sign.value
105
106            rospy.loginfo("pub_mode_return")
107            self.pub_mode_return.publish(msg_mode_return)
108
109        self.is_triggered = True
110
111    # Which step is in Level Crossing  
112    def cbLevelCrossingStamped(self, level_crossing_msg):
113        rospy.loginfo("LevelCrossing Step changed from %d", self.current_step_level_crossing)
114
115        self.current_step_level_crossing = level_crossing_msg.data
116
117        rospy.loginfo("into %d", self.current_step_level_crossing)
118
119        if self.current_step_level_crossing == self.StepOfLevelCrossing.pass_level.value:
120            self.current_mode = self.CurrentMode.level_crossing.value
121            msg_mode_return = UInt8()
122            msg_mode_return.data = self.current_mode
123            self.pub_mode_return.publish(msg_mode_return)
124
125        self.is_triggered = True
126
127    # Which step is in Tunnel
128    def cbTunnelStamped(self, tunnel_msg):
129        rospy.loginfo("Tunnel Step changed from %d", self.current_step_tunnel)
130
131        self.current_step_tunnel = tunnel_msg.data
132
133        rospy.loginfo("into %d", self.current_step_tunnel)
134
135        if self.current_step_tunnel == self.StepOfTunnel.searching_tunnel_sign.value:
136            self.current_mode = self.CurrentMode.tunnel.value
137            msg_mode_return = UInt8()
138            msg_mode_return.data = self.current_mode
139            self.pub_mode_return.publish(msg_mode_return)
140
141        self.is_triggered = True
142
143    def fnControlNode(self):
144        # lane_following
145        if self.current_mode == self.CurrentMode.lane_following.value:
146            rospy.loginfo("New trigger for lane_following")
147
148            self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
149
150            self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
151            self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
152            self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
153            self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
154            self.fnLaunch(self.Launcher.launch_detect_level.value, False)
155            self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
156
157            self.fnLaunch(self.Launcher.launch_control_lane.value, True)
158            self.fnLaunch(self.Launcher.launch_control_parking.value, False)
159            self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
160              
161        # traffic_light
162        elif self.current_mode == self.CurrentMode.traffic_light.value:
163            rospy.loginfo("New trigger for traffic_light")
164            msg_pub_traffic_light_order = UInt8()
165
166            if self.current_step_traffic_light == self.StepOfTrafficLight.searching_traffic_light.value:
167                rospy.loginfo("Current step : searching_traffic_light")
168                rospy.loginfo("Go to next step : in_traffic_light")
169
170                msg_pub_traffic_light_order.data = self.StepOfTrafficLight.in_traffic_light.value
171
172                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
173                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
174                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
175                self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
176                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
177                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
178
179                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
180                self.fnLaunch(self.Launcher.launch_control_parking.value, False)
181                self.fnLaunch(self.Launcher.launch_control_level.value, False)
182
183            elif self.current_step_traffic_light == self.StepOfTrafficLight.in_traffic_light.value:
184                rospy.loginfo("Current step : in_traffic_light")
185                rospy.loginfo("Go to next step : pass_traffic_light")
186
187                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
188                self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
189                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
190                self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
191                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
192                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
193
194                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
195                self.fnLaunch(self.Launcher.launch_control_parking.value, False)
196                self.fnLaunch(self.Launcher.launch_control_level.value, False)
197
198            rospy.sleep(2)
199
200            self.pub_traffic_light_order.publish(msg_pub_traffic_light_order)
201
202        # parking_lot
203        elif self.current_mode == self.CurrentMode.parking_lot.value:
204            rospy.loginfo("New trigger for parking_lot")
205            msg_pub_parking_lot_order = UInt8()
206
207            if self.current_step_parking_lot == self.StepOfParkingLot.searching_parking_sign.value:
208                rospy.loginfo("Current step : searching_parking_sign")
209                rospy.loginfo("Go to next step : searching_parking_point_line")
210
211                msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_parking_point_line.value
212
213                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
214                self.fnLaunch(self.Launcher.launch_control_parking.value, False)
215
216                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
217                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
218                self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
219                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
220                                   
221            elif self.current_step_parking_lot == self.StepOfParkingLot.searching_parking_point_line.value:
222                rospy.loginfo("Current step : searching_parking_point_line")
223                rospy.loginfo("Go to next step : searching_nonreserved_parking_area")
224
225                msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_nonreserved_parking_area.value
226
227                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
228                self.fnLaunch(self.Launcher.launch_control_parking.value, True)
229
230                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
231                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
232                self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
233                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
234
235            elif self.current_step_parking_lot == self.StepOfParkingLot.searching_nonreserved_parking_area.value:
236                rospy.loginfo("Current step : searching_nonreserved_parking_area")
237                rospy.loginfo("Go to next step : parking")
238
239                msg_pub_parking_lot_order.data = self.StepOfParkingLot.parking.value
240
241                self.fnLaunch(self.Launcher.launch_control_lane.value, False)
242                self.fnLaunch(self.Launcher.launch_control_parking.value, True)
243                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
244                self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
245                self.fnLaunch(self.Launcher.launch_detect_parking.value, True)
246                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
247
248            elif self.current_step_parking_lot == self.StepOfParkingLot.parking.value:
249                rospy.loginfo("Current step : parking")
250                rospy.loginfo("Go to next step : searching_parking_sign")
251
252                msg_pub_parking_lot_order.data = self.StepOfParkingLot.searching_parking_sign.value
253
254                self.fnLaunch(self.Launcher.launch_control_parking.value, False)
255                self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
256                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
257                self.fnLaunch(self.Launcher.launch_detect_parking.value, False)
258                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
259                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
260
261            rospy.sleep(2)
262
263            self.pub_parking_lot_order.publish(msg_pub_parking_lot_order)
264
265        # level_crossing
266        elif self.current_mode == self.CurrentMode.level_crossing.value:
267            rospy.loginfo("New trigger for level_crossing")
268            msg_pub_level_crossing_order = UInt8()
269
270            if self.current_step_level_crossing == self.StepOfLevelCrossing.searching_stop_sign.value:
271                rospy.loginfo("Current step : searching_stop_sign")
272                rospy.loginfo("Go to next step : searching_level")
273
274                msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.searching_level.value
275
276                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
277                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
278                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
279                self.fnLaunch(self.Launcher.launch_detect_level.value, True)
280                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
281                                   
282            elif self.current_step_level_crossing == self.StepOfLevelCrossing.searching_level.value:
283                rospy.loginfo("Current step : searching_level")
284                rospy.loginfo("Go to next step : watching_level")
285
286                msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.watching_level.value
287
288                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
289                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
290                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
291                self.fnLaunch(self.Launcher.launch_detect_level.value, True)
292                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
293
294            elif self.current_step_level_crossing == self.StepOfLevelCrossing.watching_level.value:
295                rospy.loginfo("Current step : watching_level")
296                rospy.loginfo("Go to next step : stop")
297
298                msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.stop.value
299
300                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
301                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
302                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
303                self.fnLaunch(self.Launcher.launch_detect_level.value, True)
304                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
305
306            elif self.current_step_level_crossing == self.StepOfLevelCrossing.stop.value:
307                rospy.loginfo("Current step : stop")
308                rospy.loginfo("Go to next step : pass_level")
309
310                msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.pass_level.value
311
312                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
313                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
314                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
315                self.fnLaunch(self.Launcher.launch_detect_level.value, True)
316                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
317
318            elif self.current_step_level_crossing == self.StepOfLevelCrossing.pass_level.value:
319                rospy.loginfo("Current step : pass_level")
320                rospy.loginfo("Go to next step : searching_stop_sign")
321
322                msg_pub_level_crossing_order.data = self.StepOfLevelCrossing.searching_stop_sign.value
323
324                self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
325                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
326                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
327                self.fnLaunch(self.Launcher.launch_detect_level.value, True)
328                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
329
330            rospy.sleep(2)
331
332            self.pub_level_crossing_order.publish(msg_pub_level_crossing_order)
333
334        # tunnel
335        elif self.current_mode == self.CurrentMode.tunnel.value:
336            rospy.loginfo("New trigger for tunnel")
337            msg_pub_tunnel_order = UInt8()
338
339            if self.current_step_tunnel == self.StepOfTunnel.searching_tunnel_sign.value:
340                rospy.loginfo("Current step : searching_tunnel_sign")
341                rospy.loginfo("Go to next step : go_in_to_tunnel")
342
343                msg_pub_tunnel_order.data = self.StepOfTunnel.go_in_to_tunnel.value
344
345                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
346                self.fnLaunch(self.Launcher.launch_control_lane.value, False)
347                self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, False)
348                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
349                self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
350                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
351                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
352
353                self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
354                                   
355            elif self.current_step_tunnel == self.StepOfTunnel.go_in_to_tunnel.value:
356                rospy.loginfo("Current step : go_in_to_tunnel")
357                rospy.loginfo("Go to next step : navigation")
358
359                msg_pub_tunnel_order.data = self.StepOfTunnel.navigation.value
360
361                self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, False)
362                self.fnLaunch(self.Launcher.launch_control_lane.value, False)
363                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
364                self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
365                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
366                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
367                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
368
369                self.fnLaunch(self.Launcher.launch_control_tunnel.value, True)
370
371            elif self.current_step_tunnel == self.StepOfTunnel.navigation.value:
372                rospy.loginfo("Current step : navigation")
373                rospy.loginfo("Go to next step : go_out_from_tunnel")
374
375                msg_pub_tunnel_order.data = self.StepOfTunnel.go_out_from_tunnel.value
376
377                self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
378                self.fnLaunch(self.Launcher.launch_control_lane.value, False)
379                self.fnLaunch(self.Launcher.launch_detect_sign.value, False)
380                self.fnLaunch(self.Launcher.launch_detect_lane.value, False)
381                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
382                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, False)
383                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, True)
384
385                self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
386
387            elif self.current_step_tunnel == self.StepOfTunnel.go_out_from_tunnel.value:
388                rospy.loginfo("Current step : go_out_from_tunnel")
389                rospy.loginfo("Go to next step : exit")
390
391                msg_pub_tunnel_order.data = self.StepOfTunnel.exit.value
392
393                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
394                self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
395                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
396                self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
397                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
398                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
399                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
400
401                self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
402
403            elif self.current_step_tunnel == self.StepOfTunnel.exit.value:
404                rospy.loginfo("Current step : exit")
405                rospy.loginfo("Go to next step : searching_tunnel_sign")
406
407                msg_pub_tunnel_order.data = self.StepOfTunnel.searching_tunnel_sign.value
408
409                self.fnLaunch(self.Launcher.launch_detect_tunnel.value, False)
410                self.fnLaunch(self.Launcher.launch_camera_ex_calib.value, True)
411                self.fnLaunch(self.Launcher.launch_detect_lane.value, True)
412                self.fnLaunch(self.Launcher.launch_detect_sign.value, True)
413                self.fnLaunch(self.Launcher.launch_detect_traffic_light.value, True)
414                self.fnLaunch(self.Launcher.launch_control_lane.value, True)
415                self.fnLaunch(self.Launcher.launch_detect_level.value, False)
416
417                self.fnLaunch(self.Launcher.launch_control_tunnel.value, False)
418                
419            rospy.sleep(2)
420
421            self.pub_tunnel_order.publish(msg_pub_tunnel_order)
422
423        self.is_triggered = False
424
425    def fnLaunch(self, launch_num, is_start):
426        if launch_num == self.Launcher.launch_camera_ex_calib.value:
427            if is_start == True:
428                if self.launch_camera_launched == False:
429                    self.launch_camera = roslaunch.scriptapi.ROSLaunch()
430                    self.launch_camera = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_camera/launch/turtlebot3_autorace_extrinsic_camera_calibration.launch"])
431                    self.launch_camera_launched = True
432                    self.launch_camera.start()
433                else:
434                    pass
435            else:
436                if self.launch_camera_launched == True:
437                    self.launch_camera_launched = False
438                    self.launch_camera.shutdown()
439                else:
440                    pass
441        elif launch_num == self.Launcher.launch_detect_sign.value:
442            if is_start == True:
443                if self.launch_detect_sign_launched == False:
444                    self.launch_detect_sign = roslaunch.scriptapi.ROSLaunch()
445                    self.launch_detect_sign = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_sign.launch"])
446                    self.launch_detect_sign_launched = True
447                    self.launch_detect_sign.start()
448                else:
449                    pass
450            else:
451                if self.launch_detect_sign_launched == True:
452                    self.launch_detect_sign_launched = False
453                    self.launch_detect_sign.shutdown()
454                else:
455                    pass                
456        elif launch_num == self.Launcher.launch_detect_lane.value:
457            if is_start == True:
458                if self.launch_detect_lane_launched == False:
459                    self.launch_detect_lane = roslaunch.scriptapi.ROSLaunch()
460                    self.launch_detect_lane = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_lane.launch"])
461                    self.launch_detect_lane_launched = True
462                    self.launch_detect_lane.start()
463                else:
464                    pass
465            else:
466                if self.launch_detect_lane_launched == True:
467                    self.launch_detect_lane_launched = False
468                    self.launch_detect_lane.shutdown()
469                else:
470                    pass                  
471        elif launch_num == self.Launcher.launch_control_lane.value:
472            if is_start == True:
473                if self.launch_control_lane_launched == False:
474                    self.launch_control_lane = roslaunch.scriptapi.ROSLaunch()
475                    self.launch_control_lane = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_lane.launch"])
476                    self.launch_control_lane_launched = True
477                    self.launch_control_lane.start()
478                else:
479                    pass
480            else:
481                if self.launch_control_lane_launched == True:
482                    self.launch_control_lane_launched = False
483                    self.launch_control_lane.shutdown()
484                else:
485                    pass                  
486        elif launch_num == self.Launcher.launch_detect_parking.value:
487            if is_start == True:
488                if self.launch_detect_parking_launched == False:
489                    self.launch_detect_parking = roslaunch.scriptapi.ROSLaunch()
490                    self.launch_detect_parking = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_parking.launch"])
491                    self.launch_detect_parking_launched = True
492                    self.launch_detect_parking.start()
493                else:
494                    pass
495            else:
496                if self.launch_detect_parking_launched == True:
497                    self.launch_detect_parking_launched = False
498                    self.launch_detect_parking.shutdown()
499                else:
500                    pass                  
501        elif launch_num == self.Launcher.launch_control_parking.value:
502            if is_start == True:
503                if self.launch_control_parking_launched == False:
504                    self.launch_control_parking = roslaunch.scriptapi.ROSLaunch()
505                    self.launch_control_parking = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_parking.launch"])     
506                    self.launch_control_parking_launched = True
507                    self.launch_control_parking.start()
508                else:
509                    pass
510            else:
511                if self.launch_control_parking_launched == True:
512                    self.launch_control_parking_launched = False
513                    self.launch_control_parking.shutdown()
514                else:
515                    pass
516        elif launch_num == self.Launcher.launch_detect_level.value:
517            if is_start == True:
518                if self.launch_detect_level_launched == False:
519                    self.launch_detect_level = roslaunch.scriptapi.ROSLaunch()
520                    self.launch_detect_level = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_level.launch"])     
521                    self.launch_detect_level_launched = True
522                    self.launch_detect_level.start()
523                else:
524                    pass
525            else:
526                if self.launch_detect_level_launched == True:
527                    self.launch_detect_level_launched = False
528                    self.launch_detect_level.shutdown()
529                else:
530                    pass                  
531        elif launch_num == self.Launcher.launch_detect_traffic_light.value:
532            if is_start == True:
533                if self.launch_detect_traffic_light_launched == False:
534                    self.launch_detect_traffic_light = roslaunch.scriptapi.ROSLaunch()
535                    self.launch_detect_traffic_light = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_traffic_light.launch"])     
536                    self.launch_detect_traffic_light_launched = True
537                    self.launch_detect_traffic_light.start()
538                else:
539                    pass
540            else:
541                if self.launch_detect_traffic_light_launched == True:
542                    self.launch_detect_traffic_light_launched = False
543                    self.launch_detect_traffic_light.shutdown()
544                else:
545                    pass    
546                    
547        elif launch_num == self.Launcher.launch_detect_tunnel.value:
548            if is_start == True:
549                if self.launch_detect_tunnel_launched == False:
550                    self.launch_detect_tunnel = roslaunch.scriptapi.ROSLaunch()
551                    self.launch_detect_tunnel = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_detect/launch/turtlebot3_autorace_detect_tunnel.launch"])     
552                    self.launch_detect_tunnel_launched = True
553                    self.launch_detect_tunnel.start()
554                else:
555                    pass
556            else:
557                if self.launch_detect_tunnel_launched == True:
558                    self.launch_detect_tunnel_launched = False
559                    self.launch_detect_tunnel.shutdown()
560                else:
561                    pass    
562        elif launch_num == self.Launcher.launch_control_tunnel.value:
563            if is_start == True:
564                if self.launch_control_tunnel_launched == False:
565                    self.launch_control_tunnel = roslaunch.scriptapi.ROSLaunch()
566                    self.launch_control_tunnel = roslaunch.parent.ROSLaunchParent(self.uuid, [self.ros_package_path + "turtlebot3_autorace_control/launch/turtlebot3_autorace_control_tunnel.launch"])     
567                    self.launch_control_tunnel_launched = True
568                    self.launch_control_tunnel.start()
569                else:
570                    pass
571            else:
572                if self.launch_control_tunnel_launched == True:
573                    self.launch_control_tunnel_launched = False
574                    self.launch_control_tunnel.shutdown()
575                else:
576                    pass
577
578    def main(self):
579        rospy.spin()
580
581if __name__ == '__main__':
582    rospy.init_node('core_node_controller')
583    node = CoreNodeController()
584    node.main()
585
Full Screen

aichallenge_submit_launch.launch.py

Source: aichallenge_submit_launch.launch.py Github

copy
1from ament_index_python import get_package_share_directory
2from launch import LaunchDescription
3from launch.actions import DeclareLaunchArgument
4from launch.actions import IncludeLaunchDescription
5from launch.launch_description_sources import PythonLaunchDescriptionSource
6from launch.substitutions import LaunchConfiguration
7from launch_ros.actions import Node
8
9import os
10
11
12def generate_launch_description():
13    aichallenge_sample_pkg_prefix = get_package_share_directory('aichallenge_sample')
14
15    aichallenge_sample_launch = IncludeLaunchDescription(
16        PythonLaunchDescriptionSource([aichallenge_sample_pkg_prefix, '/launch/aichallenge_sample.launch.py']),
17        launch_arguments={}.items()
18    )
19
20    return LaunchDescription([
21        aichallenge_sample_launch,
22    ])
23
Full Screen

LaunchUIComponent.js

Source: LaunchUIComponent.js Github

copy
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4  value: true
5});
6exports.LaunchUIComponent = undefined;
7
8var _string;
9
10function _load_string() {
11  return _string = require('nuclide-commons/string');
12}
13
14var _react = _interopRequireDefault(require('react'));
15
16var _AtomInput;
17
18function _load_AtomInput() {
19  return _AtomInput = require('nuclide-commons-ui/AtomInput');
20}
21
22var _UniversalDisposable;
23
24function _load_UniversalDisposable() {
25  return _UniversalDisposable = _interopRequireDefault(require('nuclide-commons/UniversalDisposable'));
26}
27
28var _nuclideUri;
29
30function _load_nuclideUri() {
31  return _nuclideUri = _interopRequireDefault(require('nuclide-commons/nuclideUri'));
32}
33
34var _nuclideDebuggerBase;
35
36function _load_nuclideDebuggerBase() {
37  return _nuclideDebuggerBase = require('../../nuclide-debugger-base');
38}
39
40var _classnames;
41
42function _load_classnames() {
43  return _classnames = _interopRequireDefault(require('classnames'));
44}
45
46function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
47
48class LaunchUIComponent extends _react.default.Component {
49
50  constructor(props) {
51    super(props);
52
53    this._handleLaunchClick = () => {
54      // TODO: perform some validation for the input.
55      const launchExecutable = this.refs.launchExecutable.getText().trim();
56      const coreDump = this.refs.coreDump.getText().trim();
57      const launchArguments = (0, (_string || _load_string()).shellParse)(this.refs.launchArguments.getText());
58      const launchEnvironmentVariables = (0, (_string || _load_string()).shellParse)(this.refs.launchEnvironmentVariables.getText());
59      const launchWorkingDirectory = this.refs.launchWorkingDirectory.getText().trim();
60      const stdinFilePath = this.refs.stdinFilePath.getText().trim();
61      const launchTarget = {
62        executablePath: launchExecutable,
63        arguments: launchArguments,
64        environmentVariables: launchEnvironmentVariables,
65        workingDirectory: launchWorkingDirectory,
66        stdinFilePath,
67        coreDump
68      };
69      // Fire and forget.
70      this.props.actions.launchDebugger(launchTarget);
71
72      (0, (_nuclideDebuggerBase || _load_nuclideDebuggerBase()).serializeDebuggerConfig)(...this._getSerializationArgs(), {
73        launchExecutable: this.state.launchExecutable,
74        launchArguments: this.state.launchArguments,
75        launchEnvironmentVariables: this.state.launchEnvironmentVariables,
76        launchWorkingDirectory: this.state.launchWorkingDirectory,
77        stdinFilePath: this.state.stdinFilePath,
78        coreDump: this.state.coreDump
79      });
80    };
81
82    this._disposables = new (_UniversalDisposable || _load_UniversalDisposable()).default();
83    this.state = {
84      launchExecutable: '',
85      launchArguments: '',
86      launchEnvironmentVariables: '',
87      launchWorkingDirectory: '',
88      stdinFilePath: '',
89      coreDump: ''
90    };
91  }
92
93  _getSerializationArgs() {
94    return [(_nuclideUri || _load_nuclideUri()).default.isRemote(this.props.targetUri) ? (_nuclideUri || _load_nuclideUri()).default.getHostname(this.props.targetUri) : 'local', 'launch', 'native'];
95  }
96
97  setState(newState) {
98    super.setState(newState);
99    this.props.configIsValidChanged(this._debugButtonShouldEnable());
100  }
101
102  _debugButtonShouldEnable() {
103    return true;
104  }
105
106  componentDidMount() {
107    (0, (_nuclideDebuggerBase || _load_nuclideDebuggerBase()).deserializeDebuggerConfig)(...this._getSerializationArgs(), (transientSettings, savedSettings) => {
108      this.setState({
109        launchExecutable: savedSettings.launchExecutable,
110        launchArguments: savedSettings.launchArguments,
111        launchEnvironmentVariables: savedSettings.launchEnvironmentVariables,
112        launchWorkingDirectory: savedSettings.launchWorkingDirectory,
113        stdinFilePath: savedSettings.stdinFilePath,
114        coreDump: savedSettings.coreDump || ''
115      });
116    });
117
118    const launchExecutableInput = this.refs.launchExecutable;
119    if (launchExecutableInput != null) {
120      launchExecutableInput.focus();
121    }
122
123    this._disposables.add(atom.commands.add('atom-workspace', {
124      'core:confirm': () => {
125        this._handleLaunchClick();
126      }
127    }));
128
129    this.props.configIsValidChanged(true);
130  }
131
132  componentWillUnmount() {
133    this._disposables.dispose();
134  }
135
136  render() {
137    // TODO: smart fill the working directory textbox.
138    // TODO: make tab stop between textbox work.
139    // Reserve tabIndex [1~10] to header portion of the UI so we start from "11" here.
140    return _react.default.createElement(
141      'div',
142      { className: 'block' },
143      _react.default.createElement(
144        'label',
145        null,
146        'Executable: '
147      ),
148      _react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
149        ref: 'launchExecutable',
150        tabIndex: '11',
151        placeholderText: 'Input the executable path you want to launch',
152        value: this.state.launchExecutable,
153        onDidChange: value => this.setState({ launchExecutable: value })
154      }),
155      _react.default.createElement(
156        'label',
157        null,
158        'Core dump file: '
159      ),
160      _react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
161        ref: 'coreDump',
162        tabIndex: '12',
163        placeholderText: 'Optional path to a core dump file to offline debug a crash',
164        value: this.state.coreDump,
165        onDidChange: value => this.setState({ coreDump: value })
166      }),
167      _react.default.createElement(
168        'div',
169        { className: 'nuclide-native-launch-small-text' },
170        'Be sure to copy the core dump to a location where Nuclide has read access. (Nuclide server does not run as root).'
171      ),
172      _react.default.createElement(
173        'div',
174        {
175          className: (0, (_classnames || _load_classnames()).default)({
176            'nuclide-native-launch-disabled': this.state.coreDump !== ''
177          }) },
178        _react.default.createElement(
179          'label',
180          null,
181          'Arguments: '
182        ),
183        _react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
184          ref: 'launchArguments',
185          tabIndex: '13',
186          disabled: this.state.coreDump !== '',
187          placeholderText: 'Arguments to the executable',
188          value: this.state.launchArguments,
189          onDidChange: value => this.setState({ launchArguments: value })
190        }),
191        _react.default.createElement(
192          'label',
193          null,
194          'Environment Variables: '
195        ),
196        _react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
197          ref: 'launchEnvironmentVariables',
198          tabIndex: '14',
199          disabled: this.state.coreDump !== '',
200          placeholderText: 'Environment variables (e.g., SHELL=/bin/bash PATH=/bin)',
201          value: this.state.launchEnvironmentVariables,
202          onDidChange: value => this.setState({ launchEnvironmentVariables: value })
203        }),
204        _react.default.createElement(
205          'label',
206          null,
207          'Working directory: '
208        ),
209        _react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
210          ref: 'launchWorkingDirectory',
211          tabIndex: '15',
212          disabled: this.state.coreDump !== '',
213          placeholderText: 'Working directory for the launched executable',
214          value: this.state.launchWorkingDirectory,
215          onDidChange: value => this.setState({ launchWorkingDirectory: value })
216        }),
217        _react.default.createElement(
218          'label',
219          null,
220          'Stdin file: '
221        ),
222        _react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, {
223          ref: 'stdinFilePath',
224          tabIndex: '16',
225          disabled: this.state.coreDump !== '',
226          placeholderText: 'Redirect stdin to this file',
227          value: this.state.stdinFilePath,
228          onDidChange: value => this.setState({ stdinFilePath: value })
229        })
230      )
231    );
232  }
233
234}
235exports.LaunchUIComponent = LaunchUIComponent; /**
236                                                * Copyright (c) 2015-present, Facebook, Inc.
237                                                * All rights reserved.
238                                                *
239                                                * This source code is licensed under the license found in the LICENSE file in
240                                                * the root directory of this source tree.
241                                                *
242                                                * 
243                                                * @format
244                                                */
Full Screen

LaunchPage.qunit.js

Source: LaunchPage.qunit.js Github

copy
1// Copyright (c) 2009-2017 SAP SE, All Rights Reserved
2/**
3 * @fileOverview QUnit tests for sap.ushell.services.LaunchPage
4 */
5sap.ui.require([
6    "sap/ushell/services/LaunchPage",
7    "sap/ushell/test/utils",
8    "sap/ushell/adapters/local/LaunchPageAdapter",
9    "sap/ushell/Config",
10    "sap/ushell/services/_ContentExtensionAdapterFactory/ContentExtensionAdapterConfig",
11    "sap/ushell/services/_ContentExtensionAdapterFactory/FeaturedGroupConfig",
12    "sap/ushell/resources"
13], function (LaunchPage, testUtils, LaunchPageAdapter, Config, AdapterFactoryConfig, FeaturedGroupMock) {
14    "use strict";
15    /*global asyncTest, deepEqual, module, throws ok, start, strictEqual, test, sinon */
16
17    var sUshellTestRootPath = jQuery.sap.getResourcePath("sap/ushell").replace("resources", "test-resources"),
18        oLastStub,
19        oGetMockAdapterConfigStub,
20        oGetConfigAdaptersStub,
21        oLaunchPageConfig = {
22            config: {
23                pathToLocalizedContentResources: sUshellTestRootPath + "/test/services/resources/resources.properties",
24                groups: [{
25                    id: "group_0",
26                    title: "test_group1",
27                    isPreset: true,
28                    isVisible: true,
29                    isGroupLocked: false,
30                    tiles: [{
31                        id: "9a6eb46c-2d10-3a37-90d8-8f49f60cb111",
32                        title: "test_tile_header",
33                        size: "1x1",
34                        tileType: "sap.ushell.ui.tile.TileBase",
35                        keywords: ["test_keywords"],
36                        properties: {
37                            chipId: "catalogTile_1",
38                            title: "test_tile_header",
39                            subtitle: "test_sub_tile_header",
40                            infoState: "Neutral",
41                            info: "test_info",
42                            icon: "sap-icon://travel-expense-report",
43                            targetURL: "#Action-todefaultapp",
44                            formFactor: "Desktop,Tablet,Phone"
45                        }
46                    },
47                        {
48                            id: "tile_001",
49                            title: "test_tile_preview_api",
50                            size: "1x1",
51                            tileType: "sap.ushell.ui.tile.TileBase",
52                            keywords: ["test_keywords"],
53                            properties: {
54                                chipId: "catalogTile_1",
55                                infoState: "Neutral",
56                                info: "test_info",
57                                formFactor: "Desktop,Tablet,Phone"
58                            }
59                        },
60                        {
61                            id: "tile_787",
62                            tileType: "sap.ushell.ui.tile.StaticTile",
63                            isLink: true,
64                            properties: {
65                                text: "I am a link!",
66                                href: "#Action-todefaultapp"
67                            }
68                        },
69                        {
70                            id: "tile_777",
71                            tileType: "sap.ushell.ui.tile.StaticTile",
72                            isLink: true,
73                            properties: {
74                                text: "I am an external link!",
75                                href: "http://www.google.com"
76                            }
77                        },
78                        {
79                            id: "tile_797",
80                            tileType: "sap.ushell.ui.tile.StaticTile",
81                            mode: "HeaderMode",
82                            properties: {
83                                title: "test_tile_header",
84                                subtitle: "test_sub_tile_header"
85                            }
86                        },
87                        {
88                            id: "tile_807",
89                            tileType: "sap.ushell.ui.tile.StaticTile",
90                            mode: "ContentMode",
91                            properties: {
92                                title: "test_tile_header",
93                                subtitle: "test_sub_tile_header"
94                            }
95                        }
96                    ]
97                }, {
98                    id: "group_1",
99                    title: "test_group2",
100                    isPreset: true,
101                    isVisible: true,
102                    isGroupLocked: false,
103                    tiles: [{}]
104                }, {
105                    id: "group_2",
106                    title: "test_group3",
107                    isPreset: true,
108                    isVisible: true,
109                    isGroupLocked: false,
110                    tiles: [
111                        {
112                            id: "tile_102",
113                            title: "Test component tile",
114                            size: "1x1",
115                            tileType: "sap.ushell.ui.tile.StaticTile",
116                            moduleName: "sap.ushell.demo.demoTiles",
117                            moduleType: "UIComponent",
118                            namespace: "sap.ushell.demo.demoTiles",
119                            path: sUshellTestRootPath + "/demoapps/demoTiles/",
120                            properties: {
121                                chipId: "catalogTile_38",
122                                title: "Test component tile",
123                                subtitle: "A tile wrapped in a component",
124                                infoState: "Neutral",
125                                info: "0 days running without bugs",
126                                icon: "sap-icon://flight",
127                                targetURL: "#Action-todefaultapp",
128                                formFactor: "Desktop,Tablet"
129                            }
130                        },
131                        {
132                            id: "tile_103",
133                            title: "Test view tile",
134                            size: "1x1",
135                            tileType: "sap.ushell.ui.tile.StaticTile",
136                            moduleName: "sap.ushell.demo.demoTiles.TestViewTile",
137                            moduleType: "JS",
138                            namespace: "sap.ushell.demo.demoTiles",
139                            path: sUshellTestRootPath + "/demoapps/demoTiles/",
140                            properties: {
141                                chipId: "catalogTile_38",
142                                title: "Test view tile",
143                                subtitle: "A tile wrapped in a view",
144                                infoState: "Neutral",
145                                info: "0 days running without bugs",
146                                icon: "sap-icon://flight",
147                                targetURL: "#Action-todefaultapp",
148                                formFactor: "Desktop,Tablet"
149                            }
150                        }
151                    ]
152                }, {
153                    id: "group_3",
154                    title: "test_group4",
155                    isPreset: true,
156                    isVisible: true,
157                    isGroupLocked: true,
158                    tiles: [{}]
159                }, {
160                    id: "group_4",
161                    title: "test_group5",
162                    isPreset: true,
163                    isVisible: false,
164                    isGroupLocked: true,
165                    tiles: [{}]
166                }],
167                catalogs: [
168                    {
169                        id: "test_catalog_01",
170                        title: "test_catalog1",
171                        tiles: [{}]
172                    }, {
173                        id: "test_catalog_02",
174                        title: "test_catalog2",
175                        tiles: [{}]
176                    }
177                ]
178            }
179        },
180        aAdditionalAdapterConfig = [{
181            name: "feature",
182            adapter: "sap.ushell.adapters.local.LaunchPageAdapter",
183            config: "/core/home/featuredGroup/enable",
184            system: {
185                alias: "",
186                platform: "local"
187            },
188            configHandler: function () {
189                var bEnableFrequentCard = true,
190                    bEnableRecentCard = true;
191                return FeaturedGroupMock.getMockAdapterConfig(bEnableFrequentCard, bEnableRecentCard);
192            }
193        }],
194        oFeatureGroupConfig = {
195            groups: [{
196                "id": "featuredArea",
197                "contentProvider": "feature",
198                "isPersonalizationLocked": function () {
199                    return true;
200                },
201                "getTitle": function () {
202                    return "Featured";
203                },
204                "title": "Featured",
205                "isFeatured": true,
206                "isPreset": true,
207                "isVisible": true,
208                "isDefaultGroup": false,
209                "isGroupLocked": true,
210                "tiles": [{
211                    "id": "tile_00",
212                    "contentProvider": "feature",
213                    "type": "recent",
214                    "title": "[FEATURED] Sales Performance",
215                    "text": "[FEATURED] Sales Performance",
216                    "size": "1x1",
217                    "tileType": "sap.ushell.ui.tile.DynamicTile",
218                    "isLinkPersonalizationSupported": false,
219                    "keywords": ["sales", "performance"],
220                    "formFactor": "Desktop,Tablet,Phone",
221                    "serviceRefreshInterval": 10,
222                    "actions": [{
223                        "text": "Go To Sample App",
224                        "icon": "sap-icon://action",
225                        "targetURL": "#Action-toappnavsample"
226                    }, {
227                        "text": "Go to stackoverflow",
228                        "icon": "sap-icon://action",
229                        "targetURL": "http://stackoverflow.com/"
230                    }, {
231                        "text": "Illigal URL",
232                        "icon": "sap-icon://action",
233                        "targetURL": "stackoverflow.com/"
234                    }, {
235                        "text": "Callback action",
236                        "icon": "sap-icon://action-settings"
237                    }],
238                    "chipId": "catalogTile_33",
239                    "properties": {
240                        "title": "[FEATURED] Sales Performance",
241                        "numberValue": 3.75,
242                        "info": "Change to Last Month in %",
243                        "numberFactor": "%",
244                        "numberDigits": 2,
245                        "numberState": "Positive",
246                        "stateArrow": "Up",
247                        "icon": "sap-icon://Fiori2/F0002",
248                        "targetURL": "#Action-toappnavsample"
249                    }
250                }, {
251                    "id": "tile_shelluiservicesample",
252                    "contentProvider": "feature",
253                    "type": "frequent",
254                    "title": "[FEATURED] ShellUIService Sample App",
255                    "size": "1x1",
256                    "tileType": "sap.ushell.ui.tile.StaticTile",
257                    "isLinkPersonalizationSupported": true,
258                    "formFactor": "Desktop,Tablet",
259                    "chipId": "catalogTile_45",
260                    "properties": {
261                        "title": "[FEATURED] Sample App for ShellUIService",
262                        "text": "[FEATURED] Sample App for ShellUIService",
263                        "subtitle": "",
264                        "infoState": "Neutral",
265                        "info": "#Action-toappshelluiservicesample",
266                        "icon": "sap-icon://syringe",
267                        "targetURL": "#Action-toappshelluiservicesample"
268                    }
269                }]
270            }]
271        };
272
273    [
274        {
275            testDescription: "when enableFeaturedGroup is true",
276            input: {
277                enableFeaturedGroup: true
278            },
279            output: {
280                numberOfFeaturedGroups: 1
281            }
282        },
283        {
284            testDescription: "when enableFeaturedGroup is false",
285            input: {
286                enableFeaturedGroup: false
287            },
288            output: {
289                numberOfFeaturedGroups: 0
290            }
291        }
292    ].forEach(function (oFixture) {
293
294        module("sap.ushell.services.LaunchPage " + oFixture.testDescription, {
295
296            beforeEach: function (assert) {
297                oLastStub = sinon.stub(Config, 'last');
298                oLastStub.withArgs("/core/spaces/enabled").returns(false);
299                oLastStub.returns(oFixture.input.enableFeaturedGroup);
300
301                oGetMockAdapterConfigStub = sinon.stub(FeaturedGroupMock, "getMockAdapterConfig").returns(
302                    oFeatureGroupConfig
303                );
304                oGetConfigAdaptersStub = sinon.stub(AdapterFactoryConfig, "_getConfigAdapters").returns(
305                    aAdditionalAdapterConfig
306                );
307            },
308            teardown: function () {
309                testUtils.restoreSpies(
310                );
311                oLastStub.restore();
312                oGetMockAdapterConfigStub.restore();
313                oGetConfigAdaptersStub.restore();
314            }
315        });
316
317        test("addBookmark failures", function () {
318            var oLaunchPageService = new LaunchPage();
319
320            // code under test and tests
321            throws(function () {
322                oLaunchPageService.addBookmark();
323            });
324            throws(function () {
325                oLaunchPageService.addBookmark("Test");
326            });
327            throws(function () {
328                oLaunchPageService.addBookmark({});
329            }, /Title missing in bookmark configuration/);
330            throws(function () {
331                oLaunchPageService.addBookmark({title: ""});
332            }, /Title missing in bookmark configuration/);
333            throws(function () {
334                oLaunchPageService.addBookmark({title: "MyTitle"});
335            }, /URL missing in bookmark configuration/);
336        });
337
338        test("addBookmark success", function () {
339            var oActualPromise,
340                oBookmarkConfig = { title: "MyTitle", url: "MyUrl" },
341                oLaunchPageAdapter = {
342                    addBookmark: sinon.stub().returns(new jQuery.Deferred().promise())
343                },
344                oLaunchPageService;
345
346            // prepare test
347            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
348
349            // code under test
350            oActualPromise = oLaunchPageService.addBookmark(oBookmarkConfig);
351
352            // test
353            ok(oLaunchPageAdapter.addBookmark.calledOnce);
354            ok(oLaunchPageAdapter.addBookmark.calledWith(oBookmarkConfig));
355            strictEqual(oActualPromise, oLaunchPageAdapter.addBookmark.returnValues[0]);
356        });
357
358        test("setTileVisible", function () {
359            var oTile = {},
360                oLaunchPageAdapter = {
361                    setTileVisible: sinon.spy()
362                },
363                oLaunchPageService;
364
365            // prepare test
366            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
367
368            // code under test
369            oLaunchPageService.setTileVisible(oTile, true);
370
371            // test
372            ok(oLaunchPageAdapter.setTileVisible.calledOnce);
373            ok(oLaunchPageAdapter.setTileVisible.calledWithExactly(oTile, true));
374        });
375
376        test("getCatalogError", function () {
377            var oCatalog = {},
378                oLaunchPageAdapter = {
379                    getCatalogError: sinon.stub().returns("foo")
380                },
381                oLaunchPageService;
382
383            // prepare test
384            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
385
386            // code under test
387            strictEqual(oLaunchPageService.getCatalogError(oCatalog), "foo");
388
389            // test
390            ok(oLaunchPageAdapter.getCatalogError.calledOnce);
391            ok(oLaunchPageAdapter.getCatalogError.calledWithExactly(oCatalog));
392        });
393
394        test("isTileIntentSupported", function () {
395            var oTile = {},
396                oLaunchPageAdapter = {
397                    isTileIntentSupported: sinon.stub().returns("foo") // deliberately no boolean
398                },
399                oLaunchPageService;
400
401            // part 1: unsupported in adapter
402            oLaunchPageService = new LaunchPage({});
403            strictEqual(oLaunchPageService.isTileIntentSupported(oTile), true);
404
405            // part 2: delegates to adapter
406            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
407            strictEqual(oLaunchPageService.isTileIntentSupported(oTile), "foo");
408            ok(oLaunchPageAdapter.isTileIntentSupported.calledOnce);
409            ok(oLaunchPageAdapter.isTileIntentSupported.calledWithExactly(oTile));
410        });
411
412        test("getCardManifest", function () {
413            var oCard = {},
414                oLaunchPageAdapter = {
415                    getCardManifest: sinon.stub().returns("Manifest")
416                },
417                oLaunchPageService;
418
419            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
420            strictEqual(oLaunchPageService.getCardManifest(oCard), "Manifest");
421            ok(oLaunchPageAdapter.getCardManifest.calledOnce);
422            ok(oLaunchPageAdapter.getCardManifest.calledWithExactly(oCard));
423        });
424
425        test("isGroupVisible", function () {
426            var oGroup = {},
427                oLaunchPageAdapter = {
428                    isGroupVisible: sinon.stub().returns("visible")
429                },
430                oLaunchPageService;
431
432            // part 1: unsupported in adapter - default value received from the service directly
433            oLaunchPageService = new LaunchPage({});
434            strictEqual(oLaunchPageService.isGroupVisible(oGroup), true);
435
436            // part 2: delegates to adapter
437            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
438            strictEqual(oLaunchPageService.isGroupVisible(oGroup), "visible");
439            ok(oLaunchPageAdapter.isGroupVisible.calledOnce);
440            ok(oLaunchPageAdapter.isGroupVisible.calledWithExactly(oGroup));
441        });
442
443        test("isGroupLocked", function () {
444            var oGroup = {},
445                oLaunchPageAdapter = {
446                    isGroupLocked: sinon.stub().returns("foo")
447                },
448                oLaunchPageService;
449
450            // part 1: unsupported in adapter - default value received from the service directly
451            oLaunchPageService = new LaunchPage({});
452            strictEqual(oLaunchPageService.isGroupLocked(oGroup), false);
453
454            // part 2: delegates to adapter
455            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
456            strictEqual(oLaunchPageService.isGroupLocked(oGroup), "foo");
457            ok(oLaunchPageAdapter.isGroupLocked.calledOnce);
458            ok(oLaunchPageAdapter.isGroupLocked.calledWithExactly(oGroup));
459        });
460
461        test("hideGroups", function () {
462            var aGroups = [],
463                oLaunchPageAdapter = {
464                    hideGroups: sinon.stub().returns({
465                        fail: function (f) {},
466                        done: function (f) { return this; }
467                    })
468                },
469                oLaunchPageService;
470
471            // part 1: unsupported in adapter - A deferred object is expected which is in failed status
472            oLaunchPageService = new LaunchPage({});
473            var oDeferred = oLaunchPageService.hideGroups([]);
474            strictEqual(oDeferred.state(), "rejected");
475
476            // part 2: delegates to adapter
477            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
478            oLaunchPageService.hideGroups(aGroups);
479            ok(oLaunchPageAdapter.hideGroups.calledOnce);
480            ok(oLaunchPageAdapter.hideGroups.calledWithExactly(aGroups));
481        });
482
483        test("getCatalogData", function () {
484            var oCatalog = {},
485                oResult = {},
486                oLaunchPageAdapter,
487                oLaunchPageService,
488                oLogMock = testUtils.createLogMock()
489                    .filterComponent("sap.ushell.services.LaunchPage")
490                    .warning("getCatalogData not implemented in adapter", null,
491                        "sap.ushell.services.LaunchPage");
492
493            // part 1: unsupported in adapter
494            oLaunchPageService = new LaunchPage({
495                getCatalogId: function (oCatalog0) {
496                    strictEqual(oCatalog0, oCatalog);
497                    return "foo";
498                }
499            });
500            deepEqual(oLaunchPageService.getCatalogData(oCatalog), {id: "foo"});
501            oLogMock.verify();
502
503            // part 2: delegates to adapter
504            oLaunchPageAdapter = {
505                getCatalogData: sinon.stub().returns(oResult)
506            };
507            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
508            strictEqual(oLaunchPageService.getCatalogData(oCatalog), oResult);
509            ok(oLaunchPageAdapter.getCatalogData.calledOnce);
510            ok(oLaunchPageAdapter.getCatalogData.calledWithExactly(oCatalog));
511        });
512
513        test("test countBookmarks", function () {
514            var oActualPromise,
515                oExpectedPromise = (new jQuery.Deferred()).promise(),
516                oLaunchPageAdapter = {
517                    countBookmarks: sinon.stub().returns(oExpectedPromise)
518                },
519                oLaunchPageService;
520
521            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
522
523            throws(function () {
524                oLaunchPageService.countBookmarks();
525            }, /Missing URL/);
526            throws(function () {
527                oLaunchPageService.countBookmarks("");
528            }, /Missing URL/);
529            throws(function () {
530                oLaunchPageService.countBookmarks({});
531            }, /Missing URL/);
532            ok(oLaunchPageAdapter.countBookmarks.notCalled);
533
534            oActualPromise = oLaunchPageService.countBookmarks("###");
535
536            strictEqual(oActualPromise, oExpectedPromise);
537            ok(oLaunchPageAdapter.countBookmarks.calledOnce);
538            strictEqual(oLaunchPageAdapter.countBookmarks.args[0][0], "###");
539        });
540
541        test("test deleteBookmarks", function () {
542            var oActualPromise,
543                oExpectedPromise = (new jQuery.Deferred()).promise(),
544                oLaunchPageAdapter = {
545                    deleteBookmarks: sinon.stub().returns(oExpectedPromise)
546                },
547                oLaunchPageService;
548
549            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
550
551            throws(function () {
552                oLaunchPageService.deleteBookmarks();
553            }, /Missing URL/);
554            throws(function () {
555                oLaunchPageService.deleteBookmarks("");
556            }, /Missing URL/);
557            throws(function () {
558                oLaunchPageService.deleteBookmarks({});
559            }, /Missing URL/);
560            ok(oLaunchPageAdapter.deleteBookmarks.notCalled);
561
562            oActualPromise = oLaunchPageService.deleteBookmarks("###");
563
564            strictEqual(oActualPromise, oExpectedPromise);
565            ok(oLaunchPageAdapter.deleteBookmarks.calledOnce);
566            strictEqual(oLaunchPageAdapter.deleteBookmarks.args[0][0], "###");
567        });
568
569        test("test updateBookmarks", function () {
570            var oActualPromise,
571                oExpectedPromise = (new jQuery.Deferred()).promise(),
572                oLaunchPageAdapter = {
573                    updateBookmarks: sinon.stub().returns(oExpectedPromise)
574                },
575                oLaunchPageService,
576                oParameters = {
577                    url: "foo"
578                };
579
580            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
581
582            throws(function () {
583                oLaunchPageService.updateBookmarks();
584            }, /Missing URL/);
585            throws(function () {
586                oLaunchPageService.updateBookmarks("");
587            }, /Missing URL/);
588            throws(function () {
589                oLaunchPageService.updateBookmarks({});
590            }, /Missing URL/);
591            throws(function () {
592                oLaunchPageService.updateBookmarks("foo");
593            }, /Missing parameters/);
594            throws(function () {
595                oLaunchPageService.updateBookmarks("foo", true);
596            }, /Missing parameters/);
597            ok(oLaunchPageAdapter.updateBookmarks.notCalled);
598
599            oActualPromise = oLaunchPageService.updateBookmarks("###", oParameters);
600
601            strictEqual(oActualPromise, oExpectedPromise);
602            ok(oLaunchPageAdapter.updateBookmarks.calledOnce);
603            strictEqual(oLaunchPageAdapter.updateBookmarks.args[0][0], "###");
604            strictEqual(oLaunchPageAdapter.updateBookmarks.args[0][1], oParameters);
605        });
606
607        test("Tile actions", function () {
608            var oTile = {},
609                aInternalActions,
610                aExternalActions1,
611                aExternalActions2,
612                oLaunchPageAdapter,
613                oLaunchPageService;
614
615
616
617            // part 1: no actions
618            oLaunchPageAdapter = {};
619            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
620
621            deepEqual(oLaunchPageService.getTileActions(oTile), []);
622
623            // part 2: internal actions
624            aInternalActions = [{text: "InternalAction1"}, {text: "InternalAction2"}];
625            oLaunchPageAdapter = {
626                getTileActions: sinon.stub().returns(aInternalActions)
627            };
628            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
629
630            deepEqual(oLaunchPageService.getTileActions(oTile), aInternalActions);
631            ok(oLaunchPageAdapter.getTileActions.calledWithExactly(oTile));
632
633            // part 3: external actions
634            aExternalActions1 = [{text: "ExternalAction11"}, {text: "ExternalAction12"}];
635            aExternalActions2 = [{text: "ExternalAction21"}, {text: "ExternalAction22"}];
636            oLaunchPageAdapter = {};
637            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
638            oLaunchPageService.registerTileActionsProvider(sinon.stub().returns(aExternalActions1));
639            oLaunchPageService.registerTileActionsProvider(sinon.stub().returns(aExternalActions2));
640
641            deepEqual(oLaunchPageService.getTileActions(oTile), aExternalActions1.concat(aExternalActions2));
642
643
644            // part 4: internal and external actions
645            aInternalActions = [{text: "InternalAction1"}, {text: "InternalAction2"}];
646            oLaunchPageAdapter = {
647                getTileActions: sinon.stub().returns(aInternalActions)
648            };
649            aExternalActions1 = [{text: "ExternalAction11"}, {text: "ExternalAction12"}];
650            aExternalActions2 = [{text: "ExternalAction21"}, {text: "ExternalAction22"}];
651            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
652            oLaunchPageService.registerTileActionsProvider(sinon.stub().returns(aExternalActions1));
653            oLaunchPageService.registerTileActionsProvider(sinon.stub().returns(aExternalActions2));
654
655            deepEqual(oLaunchPageService.getTileActions(oTile), aInternalActions.concat(aExternalActions1.concat(aExternalActions2)));
656
657            ok(oLaunchPageAdapter.getTileActions.calledWithExactly(oTile));
658        });
659
660        test("getCatalogTileTargetURL", function () {
661            var oLaunchPageService,
662                sTargetUrl,
663                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
664
665            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
666
667            // part 1: TargetUrl exist in configuration
668            sTargetUrl = oLaunchPageService.getCatalogTileTargetURL(oLaunchPageConfig.config.groups[0].tiles[0]);
669            strictEqual(sTargetUrl, oLaunchPageConfig.config.groups[0].tiles[0].properties.targetURL, "TargetUrl as expected");
670
671            // part 2: TargetUrl does not exist in configuration
672            sTargetUrl = oLaunchPageService.getCatalogTileTargetURL(oLaunchPageConfig.config.groups[0].tiles[1]);
673            strictEqual(sTargetUrl, null, "TargetUrl default value is null");
674
675        });
676
677        test("getCatalogTilePreviewTitle", function () {
678            var oLaunchPageService,
679                sPreviewTitle,
680                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
681
682            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
683
684            // part 1: Title exist in configuration
685            sPreviewTitle = oLaunchPageService.getCatalogTilePreviewTitle(oLaunchPageConfig.config.groups[0].tiles[0]);
686            strictEqual(sPreviewTitle, oLaunchPageConfig.config.groups[0].tiles[0].properties.title, "Preview title as expected");
687
688            // part 2: Title does not exist in configuration
689            sPreviewTitle = oLaunchPageService.getCatalogTilePreviewTitle(oLaunchPageConfig.config.groups[0].tiles[1]);
690            strictEqual(sPreviewTitle, null, "Preview title default value is null");
691
692        });
693
694        test("getCatalogTilePreviewInfo", function () {
695            // Arrange
696            var oLaunchPageService,
697                sPreviewInfo,
698                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
699
700            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
701
702            // Act
703            sPreviewInfo = oLaunchPageService.getCatalogTilePreviewInfo(oLaunchPageConfig.config.groups[0].tiles[0]);
704
705            // Assert
706            strictEqual(sPreviewInfo, oLaunchPageConfig.config.groups[0].tiles[0].properties.info, "The function getCatalogTilePreviewInfo returns the correct catalog tile preview info.");
707        });
708
709        test("getCatalogTilePreviewSubtitle", function () {
710            var oLaunchPageService,
711                sPreviewSubtitle,
712                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
713
714            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
715
716            // part 1: Title exist in configuration
717            sPreviewSubtitle = oLaunchPageService.getCatalogTilePreviewSubtitle(oLaunchPageConfig.config.groups[0].tiles[0]);
718            strictEqual(sPreviewSubtitle, oLaunchPageConfig.config.groups[0].tiles[0].properties.subtitle, "Preview subtitle as expected");
719
720            // part 2: Title does not exist in configuration
721            sPreviewSubtitle = oLaunchPageService.getCatalogTilePreviewSubtitle(oLaunchPageConfig.config.groups[0].tiles[1]);
722            strictEqual(sPreviewSubtitle, null, "Preview subtitle default value is null");
723
724        });
725
726        test("getCatalogTilePreviewIcon", function () {
727            var oLaunchPageService,
728                sPreviewIcon,
729                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
730
731            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
732
733            // part 1: Title exist in configuration
734            sPreviewIcon = oLaunchPageService.getCatalogTilePreviewIcon(oLaunchPageConfig.config.groups[0].tiles[0]);
735            strictEqual(sPreviewIcon, oLaunchPageConfig.config.groups[0].tiles[0].properties.icon, "Preview icon as expected");
736
737            // part 2: Title does not exist in configuration
738            sPreviewIcon = oLaunchPageService.getCatalogTilePreviewIcon(oLaunchPageConfig.config.groups[0].tiles[1]);
739            strictEqual(sPreviewIcon, null, "Preview icon default value is null");
740
741        });
742
743        asyncTest("getCatalogWithTranslation", function () {
744            var oLaunchPageService,
745
746            oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
747            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
748            oLaunchPageService.getCatalogs().done(function (aCatalogs) {
749                start();
750                strictEqual(aCatalogs[0].title, "Translated Catalog 1", "Correct catalog [0] title");
751                strictEqual(aCatalogs[1].title, "Translated Catalog 2", "Correct catalog [1] title");
752            });
753        });
754
755        asyncTest("getGroupsWithTranslation", function () {
756            var oLaunchPageService,
757
758                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
759            // part 1: unsupported in adapter
760            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
761            oLaunchPageService.getGroups().done(function (aGroups) {
762                start();
763                strictEqual(aGroups[0].title, "Translated Group 1", "Group translation error for aGroups[0].title");
764                strictEqual(aGroups[1].title, "Translated Group 2", "Group translation error for aGroups[1].title");
765            });
766        });
767
768        asyncTest("getGroupsWithFeatureGroup", function () {
769
770            var iNumFeaturedGroups,
771
772                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
773                oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
774                oLaunchPageService.getGroups().done(function (aGroups) {
775                    start();
776                    iNumFeaturedGroups = aGroups.filter(function (oGroup) {
777                        return oGroup.contentProvider === "feature";
778                    }).length;
779                    strictEqual(iNumFeaturedGroups, oFixture.output.numberOfFeaturedGroups, "feature group loaded");
780            });
781        });
782
783        asyncTest("getViewDataWithTranslation", function () {
784            var oLaunchPageService,
785
786                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
787            // part 1: unsupported in adapter
788            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
789            oLaunchPageService.getTileView(oLaunchPageConfig.config.groups[0].tiles[0]).done(function (oView) {
790                start();
791                strictEqual(oView.getProperty("title"), "Translated Header title", "Translated title check");
792                strictEqual(oView.getProperty("subtitle"), "Translated Sub Title", "Translated Sub Title");
793                strictEqual(oView.getProperty("info"), "Translated Info", "Translated Info");
794                strictEqual(oLaunchPageConfig.config.groups[0].tiles[0].keywords[0], "Translated Keyword", "Translated keywords");
795            });
796
797        });
798
799        asyncTest("getViewForComponentTile", function () {
800            var oLaunchPageService,
801
802                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
803            // part 1: unsupported in adapter
804            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
805            oLaunchPageService.getTileView(oLaunchPageConfig.config.groups[2].tiles[0]).done(function (oTileUI) {
806                start();
807                ok(oTileUI.getMetadata().getName() === "sap.ui.core.ComponentContainer", "Module path registered and Component wrapped with ComponentContainer");
808            });
809
810        });
811
812        asyncTest("getViewForViewTileTile", function () {
813            var oLaunchPageService,
814
815                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
816            // part 1: unsupported in adapter
817            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
818            oLaunchPageService.getTileView(oLaunchPageConfig.config.groups[2].tiles[1]).done(function (oTileUI) {
819                start();
820                ok(oTileUI.getMetadata().getName() === "sap.ui.core.mvc.JSView", "Modelu path registered and View tile retreived");
821            });
822
823        });
824
825        asyncTest("getViewForHeaderModeTile", function () {
826            var oLaunchPageService,
827                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
828
829            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
830            oLaunchPageService.getTileView(oLaunchPageConfig.config.groups[0].tiles[4]).done(function (oTileUI) {
831                start();
832                ok(oTileUI.getProperty("mode") === "HeaderMode", "Tile is in Header Mode");
833            });
834        });
835
836        asyncTest("getViewForContentModeTile", function () {
837            var oLaunchPageService,
838                oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig);
839
840            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
841            oLaunchPageService.getTileView(oLaunchPageConfig.config.groups[0].tiles[5]).done(function (oTileUI) {
842                start();
843                ok(oTileUI.getProperty("mode") === "ContentMode", "Tile is in Content Mode");
844            });
845        });
846
847        test("isLinkPersonalizationSupported", function () {
848            var oTile = {},
849                oLaunchPageAdapter = {
850                    isLinkPersonalizationSupported: sinon.stub().returns(true)
851                },
852                oLaunchPageService;
853
854            oLaunchPageService = new LaunchPage({});
855            strictEqual(oLaunchPageService.isLinkPersonalizationSupported(oTile), false);
856
857            oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
858            strictEqual(oLaunchPageService.isLinkPersonalizationSupported(oTile), true);
859            ok(oLaunchPageAdapter.isLinkPersonalizationSupported.calledOnce);
860            ok(oLaunchPageAdapter.isLinkPersonalizationSupported.calledWithExactly(oTile));
861        });
862
863        test("getCatalogTileView", function () {
864            var oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
865            oLaunchPageService = new LaunchPage(oLaunchPageAdapter),
866            oTileData = {
867                namespace: undefined,
868                path: undefined,
869                moduleType: undefined,
870                tileType: "tileTypePart1.tileTypePart2.tileTypePart3",
871                properties: {
872                    title: "title",
873                    subtitle: "subTitle",
874                    info: "info",
875                    targetURL: "#a-b"
876                }
877            },
878            oView,
879            oViewConstructor = function (oProps) {
880                var oViewObject = {
881                    oViewProperties: oProps
882                };
883
884                return oViewObject;
885            },
886            oHandleTilePressStub = sinon.stub(oLaunchPageAdapter, "_handleTilePress").returns({}),
887            oApplyDynamicTileIfoStateStub = sinon.stub(oLaunchPageAdapter, "_applyDynamicTileIfoState").returns({}),
888            oJQuaryRequireStub = sinon.stub(jQuery.sap, "require"),
889            oJQuaryGetObjectStub = sinon.stub(jQuery.sap, "getObject").callsFake( function (sObjectPath) {
890                if (sObjectPath === "tileTypePart1.tileTypePart2.tileTypePart3") {
891                    return oViewConstructor;
892                }
893            }),
894            oRiginalSapUiRequire = sap.ui.require;
895
896            sap.ui.require = sinon.spy();
897
898            oView = oLaunchPageService.getCatalogTileView(oTileData);
899
900            ok(sap.ui.require.called, "sap.ui.require is called");
901            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");
902
903            ok(oJQuaryGetObjectStub.calledTwice === true, "sap.ui.getObject calledTwice");
904            ok(oJQuaryGetObjectStub.args[0][0] === "tileTypePart1.tileTypePart2.tileTypePart3", "1st call to sap.ui.getObject for tileTypePart1.tileTypePart2.tileTypePart3");
905            ok(oJQuaryGetObjectStub.args[1][0] === "tileTypePart1.tileTypePart2.tileTypePart3", "2nd call to sap.ui.getObject for tileTypePart1.tileTypePart2.tileTypePart3");
906
907            ok(oHandleTilePressStub.calledOnce === true, "_handleTilePressStub called once");
908            ok(oApplyDynamicTileIfoStateStub.calledOnce === true, "_applyDynamicTileIfoState called once");
909            ok(oView.oViewProperties.title === "title", "Returned view title is correct");
910
911            sap.ui.require = oRiginalSapUiRequire;
912            oJQuaryRequireStub.restore();
913            oJQuaryGetObjectStub.restore();
914            oHandleTilePressStub.restore();
915            oApplyDynamicTileIfoStateStub.restore();
916        });
917
918        asyncTest("getCatalogTileViewControl", function () {
919            var oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
920                oLaunchPageService = new LaunchPage(oLaunchPageAdapter),
921                oTileData = {
922                    namespace: undefined,
923                    path: undefined,
924                    moduleType: undefined,
925                    tileType: "tileTypePart1.tileTypePart2.tileTypePart3",
926                    properties: {
927                        title: "title",
928                        subtitle: "subTitle",
929                        info: "info",
930                        targetURL: "#a-b"
931                    }
932                },
933                oViewConstructor = function (oProps) {
934                    var oViewObject = {
935                        oViewProperties: oProps
936                    };
937
938                    return oViewObject;
939                },
940                oOrigRequire = sap.ui.require,
941                oGetImageContentStub = sinon.stub(oLaunchPageAdapter, "_getImageContent").returns({
942                    addStyleClass: function () {}
943                }),
944                oRequireStub = sinon.stub(sap.ui, "require").callsFake( function (aRequirePath, fCallback) {
945                    fCallback(oViewConstructor);
946                }),
947                oHandleTilePressStub = sinon.stub(oLaunchPageAdapter, "_handleTilePress").returns({}),
948                oApplyDynamicTileIfoState = sinon.stub(oLaunchPageAdapter, "_applyDynamicTileIfoState").returns({});
949
950            oLaunchPageService.getCatalogTileViewControl(oTileData).done(function (oView) {
951                start();
952
953                ok(oRequireStub.callCount === 1, "sap.ui.require called");
954                ok(oRequireStub.args[0][0][0] === "tileTypePart1/tileTypePart2/tileTypePart3", "sap.ui.require called for tileTypePart1/tileTypePart2/tileTypePart3");
955                ok(oHandleTilePressStub.calledOnce === true, "_handleTilePressStub called once");
956                ok(oApplyDynamicTileIfoState.calledOnce === true, "_applyDynamicTileIfoState called once");
957                ok(oView.oViewProperties.title === "title", "Returned view title is correct");
958
959                sap.ui.require = oOrigRequire;
960                oGetImageContentStub.restore();
961                oHandleTilePressStub.restore();
962                oApplyDynamicTileIfoState.restore();
963            });
964        });
965
966        test("getCatalogTileViewRedirect", function () {
967            var oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
968                oLaunchPageService = new LaunchPage(oLaunchPageAdapter),
969                oGetCatalogTileViewStub;
970
971            oLaunchPageAdapter.getCatalogTileViewControl = undefined;
972
973            oGetCatalogTileViewStub = sinon.stub(oLaunchPageAdapter, "getCatalogTileView").returns({text: "viewText"});
974
975            oLaunchPageService.getCatalogTileViewControl().done(function (obj) {
976                ok(oLaunchPageAdapter.getCatalogTileView.calledOnce === true, "When adapter function getCatalogTileViewControl does not exist - getCatalogTileView is called");
977                ok(obj.text === "viewText", "Correct returned object");
978                oGetCatalogTileViewStub.restore();
979            });
980        });
981    });
982
983    asyncTest("getGroupsForBookmarks when part of the groups are locked or not visable", function () {
984
985        var oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
986        oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
987
988        oLaunchPageService.getGroupsForBookmarks().done(function (aGroups) {
989            start();
990
991            strictEqual(aGroups.length, 3, "groups were filtered correctly");
992            strictEqual(aGroups[0].title, "My Home", "title was changed correctly");
993        });
994    });
995
996    module("getGroups", function () {
997        asyncTest("getGroups with pages enabled should return a promise resolving to an empty array",  function() {
998            var oConfigStub = sinon.stub(Config, "last");
999            oConfigStub.withArgs("/core/spaces/enabled").returns(true);
1000
1001            var oLaunchPageAdapter = new LaunchPageAdapter(undefined, undefined, oLaunchPageConfig),
1002                oLaunchPageService = new LaunchPage(oLaunchPageAdapter);
1003            oLaunchPageService.getGroups().done(function (aGroups) {
1004                strictEqual(aGroups.length, 0, "an empty array is returned");
1005                start();
1006            });
1007        });
1008    });
1009});
Full Screen