1 """
2 This module represents a device.
3
4 Computer Systems Architecture Course
5 Assignment 1
6 March 2016
7 """
8
9 from threading import Event, Thread
10
11
13 """
14 Class that represents a device.
15 """
16
17 - def __init__(self, device_id, sensor_data, supervisor):
18 """
19 Constructor.
20
21 @type device_id: Integer
22 @param device_id: the unique id of this node; between 0 and N-1
23
24 @type sensor_data: List of (Integer, Float)
25 @param sensor_data: a list containing (location, data) as measured by this device
26
27 @type supervisor: Supervisor
28 @param supervisor: the testing infrastructure's control and validation component
29 """
30 self.device_id = device_id
31 self.sensor_data = sensor_data
32 self.supervisor = supervisor
33 self.script_received = Event()
34 self.scripts = []
35 self.timepoint_done = Event()
36 self.thread = DeviceThread(self)
37 self.thread.start()
38
40 """
41 Pretty prints this device.
42
43 @rtype: String
44 @return: a string containing the id of this device
45 """
46 return "Device %d" % self.device_id
47
49 """
50 Setup the devices before simulation begins.
51
52 @type devices: List of Device
53 @param devices: list containing all devices
54 """
55
56 pass
57
59 """
60 Provide a script for the device to execute.
61
62 @type script: Script
63 @param script: the script to execute from now on at each timepoint; None if the
64 current timepoint has ended
65
66 @type location: Integer
67 @param location: the location for which the script is interested in
68 """
69 if script is not None:
70 self.scripts.append((script, location))
71 self.script_received.set()
72 else:
73 self.timepoint_done.set()
74
76 """
77 Returns the pollution value this device has for the given location.
78
79 @type location: Integer
80 @param location: a location for which obtain the data
81
82 @rtype: Float
83 @return: the pollution value
84 """
85 return self.sensor_data[location] if location in self.sensor_data else None
86
88 """
89 Sets the pollution value stored by this device for the given location.
90
91 @type location: Integer
92 @param location: a location for which to set the data
93
94 @type data: Float
95 @param data: the pollution value
96 """
97 if location in self.sensor_data:
98 self.sensor_data[location] = data
99
101 """
102 Instructs the device to shutdown (terminate all threads). This method
103 is invoked by the tester. This method must block until all the threads
104 started by this device terminate.
105 """
106 self.thread.join()
107
108
110 """
111 Class that implements the device's worker thread.
112 """
113
115 """
116 Constructor.
117
118 @type device: Device
119 @param device: the device which owns this thread
120 """
121 Thread.__init__(self, name="Device Thread %d" % device.device_id)
122 self.device = device
123
159