File size: 8,777 Bytes
4b876a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/usr/bin/env python
# -*- coding:utf-8 -*-

""" This scripts is the first attempt to create a controller node for our project.

It is in charge of interpreting the simulation parameters, reacting to events from 
the robots and sending back control events. 

May the Force be with us. """

from Component import Component
from Graph import Graph
from State import State
from Task import Task
from RobotHandler import RobotHandler
from ebc.msg import Event
from ebc.msg import Task as TaskMsg
import rospy
import sys
import json
import roslaunch



class Controller ( Component ):
    """
    This is a controller. It is a runnable component of our project.
    It ensures that the system will perform the tasks.
    """ 
    
    def loadConfig( self ):
        """ This method load the config file """
        
        config_file_n = rospy.get_param( 'config_file_name' )
        
        try:
            self.config = json.load( open ( config_file_n, 'r' ) )
            
        except:
            e = sys.exc_info()[0]
            self.display("Error opening config file. %s" % e)
            raise
            
            
            
    def createListGraph( self, sectors ):
        """
        This method will create the list of Graph object that will represent the environment
        
        Returns :
        - graph  -- a list of Graph objects
        """
        graph = []
        for sector in sectors:
        
            graph.append( Graph( sector ) )
            
        return graph
            
            
            
    def linkGraphs ( self ):
        """ 
        This method will link all the Graph objects
        """
        # Link all graphs object with their nexts sectors
        for graph in self.graph:
            next = []
            for next_id in graph.next_ids:
                for next_graph in self.graph:
                    if next_graph.id == next_id:
                        next.append( next_graph )
                        
            graph.next = next
            
        # Now we only need the reference of the home sectors to describe the whole graph
        self.graph = self.graph[0] 

        
            
    def loadGraph( self ):
        """ This method creates the graph object to represent the environment """

        sectors = self.config[ 'graph' ]['sectors'] # To this date we only use the sectors
        self.graph = self.createListGraph( sectors )
        self.linkGraphs()
        
        
        
    def robot_callback( self, msg ):
        """
        Reacts to a event from a robot : updates the state
        """
        # If the robot crosses a border, we change the state
        # if the robot is displaying EOS or Gr, we do not change the state of the controller
        if msg.event != Event.EOS and msg.event != Event.G:
            # update the state
            
            # If the robot has finished the task
            if not self.robot_handlers[msg.robot_id].task:
                self.display( "No task running for robot " + str( msg.robot_id ) )
                self.state.P[msg.robot_id] = 0
                self.state.R[msg.robot_id] = self.robot_handlers[msg.robot_id].nextSector() # returns the "home" value
                self.state.N[msg.robot_id] = self.robot_handlers[msg.robot_id].nextSector()    
                
            else:
                self.display( "Task running for robot " + str( msg.robot_id ) )
                self.state.P[msg.robot_id] += 1
                self.state.R[msg.robot_id] = self.state.N[msg.robot_id]
                self.state.N[msg.robot_id] = self.robot_handlers[msg.robot_id].nextSector()
                
                self.robot_handlers[msg.robot_id].changeSector()
               
        self.display ( "Received event from " + str(msg.robot_id) + ": " + str( msg.event ) )
        
        
        
    def createRobots( self ):
        """
        This method will creates all the node corresponding to robots
        and store process handlers in an array.
        It will also creates the corresponding topics.
        """
        
        package = "ebc"
        executable = "Robot.py"
        name_base = "robot"
        
        launch = roslaunch.scriptapi.ROSLaunch()
        launch.start()
        
        self.robot_handlers = []
        for i in range( 0, self.config["performers"]["quantity"] ):
            self.robot_handlers.append( RobotHandler( name_base+str(i), launch, self ) )

        return
            
            
    
    def loadTasks( self ):
        """
        This load the task and creates a stack of tasks
        """
        self.tasks = []
        for task in self.config["tasks"]:
            self.tasks.append( Task( task ) )
            
        self.next_assigned_task_index = 0
        
        return
        
                
        
    def sendTask( self, robot, task ):
        """
        Assign and send a task to the robot
        """
        # Wait until all robots are available
        while not ( self.task_pub.get_num_connections() >= self.config["performers"]["quantity"] ):
            rospy.sleep( 0.1 )
            
        # publish message
        self.task_pub.publish( robot.id, str(task) )
        
        self.robot_handlers[robot.id].assignTask( task, self.next_assigned_task_index )
        
        # update the state
        self.state.P[ robot.id ] = 0
        self.state.R[ robot.id ] = str( task.sectors[ 0 ] )
        self.state.N[ robot.id ] = str(task.sectors[ 1 ])
    
        self.display( "Sent task " 
                    + str(self.next_assigned_task_index)
                    + " to robot " 
                    + str(robot.id) )
                    

            
            
            
    def dispatchTasks( self ):
        """
        This method will take the unfinished tasks from the pool of tasks and 
        assign them to unoccupied robots
        """
        # For each unoccupied robots
        for robot in self.robot_handlers:
            if robot.acceptTask:
                # assign an unassigned task( if there are any)
                if self.next_assigned_task_index < len( self.tasks ): 
                    self.sendTask( robot, self.tasks[ self.next_assigned_task_index ] )
                    self.next_assigned_task_index += 1
                else:
                    break
                    
        # Check if all tasks are finished
        if self.next_assigned_task_index == len( self.tasks ):
            all_tasks_done = True
            for robot in self.robot_handlers:
                if not robot.acceptTask:
                    all_tasks_done = False # At least one robot is busy
                    break
                    
            if all_tasks_done:
                # Say goodbye and quit
                self.display( "Controller has successfully performed all operations, \"Yeeeeehaaaa\" if I may say so." )
                self.stop()
            
        
    
    def setup ( self ):
        """ Here we set up the simulation parameters for the controller """
        self.loadConfig() # Load the config file
        
        # creates the robot handler objects
        self.createRobots()
        
        # initialize the state
        self.state = State( self.config, len( self.robot_handlers ), len( self.config["graph"] ) )
        
        # Publish our name to the parameters server
        rospy.set_param( 'controller_name', rospy.get_name() )
        
        # Create our control publish
        self.event_pub = rospy.Publisher( rospy.get_name(), Event, latch=True )
        
        # creates the graph object
        self.loadGraph()
        
        # Creates and dispatch the task messages
        self.task_pub = rospy.Publisher( "/tasks", TaskMsg, latch=True ) # important to latch
        self.loadTasks()
        self.dispatchTasks()
                

        


    def loopHook(self):
        """ The loop hook is called by the loop() method """
        
        # See if we can fire any control event (grant)
        events = self.state.nextEvent()
        if events:
            for event in events:
                self.event_pub.publish( event )
    
        # See if there is any unoccupied robot
        self.dispatchTasks()
        
        # Print and that's it
        self.display( str( self.state ) )
        
        return       
                
                
    def stop( self ):
        """
        This is the cleanup function
        """
            
        for robot_handler in self.robot_handlers:
            robot_handler.stop()
            
            
        sys.exit()
            
            
            
            
if __name__ == "__main__":
    ctrl = Controller ( "controller" )
    ctrl.start()
    ctrl.loop(0.5)