1 package SpeakerController;
3 // IoT Runtime packages
4 import iotruntime.slave.IoTSet;
5 import iotruntime.slave.IoTRelation;
6 //import iotcode.annotation.*;
9 import iotcode.interfaces.*;
10 import iotcode.annotation.*;
13 // Standard Java packages
14 import java.util.HashMap;
16 import java.util.List;
17 import java.util.ArrayList;
19 import java.util.Date; // TODO: Get rid of all depreciated stuff for date, switch to Calender
20 import java.util.concurrent.Semaphore;
21 import java.util.concurrent.atomic.AtomicBoolean;
22 import java.util.Random;
25 import java.rmi.RemoteException;
26 import java.rmi.server.UnicastRemoteObject;
28 // Checker annotations
29 //import iotchecker.qual.*;
31 /** Class SpeakerController for the smart home application benchmark
33 * This controller controls speakers and streams music based on
34 * GPS-like input from a phone app that notifies the controller
35 * about the position of the person
37 * @author Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
41 public class SpeakerController extends UnicastRemoteObject implements GPSGatewayCallback, SpeakerCallback {
46 public static final int CHECK_TIME_WAIT_MSEC = 100; // 1 means 1 x 100 = 0.1 second
47 public static final String MUSIC_FILE_DIRECTORY = "./music/"; // file that the music files are in
48 public static final int CURRENT_POSITION_SAMPLE_THRESHOLD = (int)((long)((long)3 * (long)CHECK_TIME_WAIT_MSEC * (long)44100) / (long)1000);
53 @config private IoTSet < GPSGatewaySmart > gpsSet;
54 @config private IoTSet < SpeakerSmart > speakerSet;
57 * IoT Sets of Things that are not devices such as rooms
59 @config private IoTSet < RoomSmart > audioRooms;
64 @config private IoTRelation < RoomSmart, SpeakerSmart > roomSpeakerRel;
67 * The state that the room main lights are supposed to be in
69 Map < RoomSmart, Boolean > roomSpeakersOnOffStatus = new HashMap < RoomSmart, Boolean > ();
71 // used to notify if new data is available
72 private AtomicBoolean newDataAvailable = new AtomicBoolean(false);
74 // the settings from the interface, used to setup the system
75 private int roomIdentifier = 0;
76 private boolean ringStatus = false;
78 // playback state variables
79 private int currentPosition = 0;
80 private AtomicBoolean playbackDone = new AtomicBoolean(false);
83 public SpeakerController() throws RemoteException {
88 /** Callback method for when room ID is retrieved.
90 * @param _roomIdentifier [int].
91 * @return [void] None.
93 public void newRoomIDRetrieved(int _roomIdentifier) {
95 roomIdentifier = _roomIdentifier;
96 System.out.println("DEBUG: New room ID is retrieved from phone!!! Room: " + roomIdentifier);
98 // new data available so set it to true
99 newDataAvailable.set(true);
103 /** Callback method for when ring status is retrieved.
105 * @param _ringStatus [boolean].
106 * @return [void] None.
108 public void newRingStatusRetrieved(boolean _ringStatus) {
110 ringStatus = _ringStatus;
111 System.out.println("DEBUG: New ring status is retrieved from phone!!! Status: " + ringStatus);
113 // new data available so set it to true
114 newDataAvailable.set(true);
118 /** Callback method when a speaker has finished playing what is in its audio buffer.
120 * @return [void] None.
122 public void speakerDone() {
123 for (SpeakerSmart speakers : speakerSet.values()) {
124 playbackDone.set(true);
129 /*******************************************************************************************************************************************
131 ** Private Helper Methods
133 *******************************************************************************************************************************************/
136 * Update speakers action based on the updated speakers status
138 private void updateSpeakersAction() {
140 // Stream music on speakers based on their status
141 for (RoomSmart room : audioRooms.values()) {
143 // Check status of the room
144 if (roomSpeakersOnOffStatus.get(room)) {
146 // used to get the average of the speakers position
147 long currPosTotal = 0;
148 long currPosCount = 0;
150 // Get the speaker objects one by one assuming that we could have
151 // more than one speaker per room
152 for (SpeakerSmart speakers : roomSpeakerRel.get(room)) {
153 System.out.println("DEBUG: Turn on speaker!");
154 // start the speaker playback if the speaker is not playing yet
155 if (!speakers.getPlaybackState()) {
157 System.out.println("Turning a speaker On in room: " + room.getRoomID());
158 speakers.startPlayback();
159 speakers.setPosition(currentPosition);
162 // get average of the positions
163 currPosTotal += speakers.getPosition();
168 if (currPosCount != 0) {
170 // get average position of the speakers
171 int currentPosOfSpeakers = (int)(currPosTotal / currPosCount);
173 // check how close we are to the correct position
174 if (Math.abs(currentPosOfSpeakers - currentPosition) > CURRENT_POSITION_SAMPLE_THRESHOLD) {
175 // we were kind of far so update all the positions
177 for (SpeakerSmart speakers : roomSpeakerRel.get(room)) {
178 speakers.setPosition(currentPosOfSpeakers);
182 // update the current position
183 currentPosition = currentPosOfSpeakers;
189 // Room status is "off"
191 // used to get the average of the speakers position
192 long currPosTotal = 0;
193 long currPosCount = 0;
195 // Get the speaker objects one by one assuming that we could have
196 // more than one speaker per room
197 for (Speaker speakers : roomSpeakerRel.get(room)) {
198 // System.out.println("DEBUG: Turn off speaker!");
200 // Turning off speaker if they are still on
201 if (speakers.getPlaybackState()) {
202 System.out.println("Turning a speaker off");
204 currPosTotal += (long)speakers.getPosition();
206 boolean tmp = speakers.stopPlayback();
209 System.out.println("Error Turning off");
213 } catch (RemoteException e) {
218 // get the average current position of the speakers
219 // so we can resume other speakers from same position
220 if (currPosCount != 0) {
221 currentPosition = (int)(currPosTotal / currPosCount);
226 // a speaker has finished playing and so we should change all the audio buffers
227 if (playbackDone.get()) {
229 // song done so update the audio buffers
231 playbackDone.set(false);
237 * Update speakers status based on room ID and ring status information from phone
239 private void updateSpeakersStatus() {
241 // If we have new data, we update the speaker streaming
242 if (newDataAvailable.get()) {
244 System.out.println("DEBUG: New data is available!!!");
245 System.out.println("DEBUG: Ring status: " + ringStatus);
246 // Check for ring status first
249 // Turn off all speakers if ring status is true (phone is ringing)
250 for (RoomSmart room : audioRooms.values()) {
252 System.out.println("DEBUG: Update status off for speakers! Phone is ringing!!!");
254 roomSpeakersOnOffStatus.put(room, false);
258 // Phone is not ringing... just play music on the right speaker
260 // Check for every room
261 for (RoomSmart room : audioRooms.values()) {
263 // Turn on the right speaker based on room ID sent from phone app
264 // Stream audio to a speaker based on room ID
265 if (room.getRoomID() == roomIdentifier) {
267 System.out.println("DEBUG: This room ID: " + room.getRoomID());
268 System.out.println("DEBUG: Turn on the speaker(s) in this room!!!");
269 // Set speaker status to on
270 roomSpeakersOnOffStatus.put(room, true);
273 // for the rooms whose IDs aren't equal to roomIdentifier
275 System.out.println("DEBUG: Turn on speaker!");
276 // Set speaker status to off
277 roomSpeakersOnOffStatus.put(room, false);
281 // Finish processing data - put this back to false
282 newDataAvailable.set(false);
287 * Prepare the speakers for a new song to start playing
289 private void prepareNextSong() {
290 System.out.println("Starting Music Prep");
292 System.out.println("Stopping all device playback");
293 // stop all devices that are still playing and clear their buffers
294 // they are about to end playback anyways
295 for (SpeakerSmart speakers : speakerSet.values()) {
298 if (speakers.getPlaybackState()) {
299 speakers.stopPlayback();
301 speakers.clearData();
302 } catch (Exception e) {
307 // get the music file names that are in the music files directory
308 File musicFolder = new File(MUSIC_FILE_DIRECTORY);
309 File[] audioFiles = musicFolder.listFiles();
310 List<String> audioFileNames = new ArrayList<String>();
312 // put all names in a list
313 for (int i = 0; i < audioFiles.length; i++) {
314 if (audioFiles[i].isFile()) {
316 audioFileNames.add(audioFiles[i].getCanonicalPath());
317 } catch (Exception ex) {
318 ex.printStackTrace();
323 // pick a random file to play
324 Random rand = new Random(System.nanoTime());
325 String audioFilename = audioFileNames.get(rand.nextInt(audioFileNames.size()));
327 System.out.println("Going to load audio file");
328 System.out.println(audioFilename);
330 // decode the mp3 file
331 System.out.println("Starting Decode");
332 MP3Decoder dec = new MP3Decoder(audioFilename);
333 List<short[]> dat = dec.getDecodedFrames();
334 System.out.println("Ending Decode");
338 // count the number of samples
340 for (short[] d : dat) {
344 // make into a single large buffer for 1 large RMI call
345 short[] compressedArray = new short[count];
347 for (short[] d : dat) {
349 compressedArray[count] = s;
355 System.out.println("Loading Speakers");
356 // send the new data to all the speakers
357 for (SpeakerSmart speakers : speakerSet.values()) {
358 System.out.println("Loading a single speaker with data");
360 speakers.loadData(compressedArray, 0, compressedArray.length);
361 } catch (Exception e) {
364 System.out.println("Done loading a single speaker with data");
367 System.out.println("All Speakers done loading");
373 /********************************************************************************************************
374 ** Public methods, called by the runtime
375 *********************************************************************************************************/
377 /** Initialization method, called by the runtime (effectively the main of the controller)
378 * This method runs a continuous loop and is blocking
380 * @return [void] None;
382 public void init() throws RemoteException, InterruptedException {
384 // Initialize the rooms
385 for (RoomSmart room : audioRooms.values()) {
386 // All rooms start with the speakers turned off
387 roomSpeakersOnOffStatus.put(room, false);
390 // Setup the cameras, start them all and assign each one a motion detector
391 for (GPSGatewaySmart gw : gpsSet.values()) {
394 gw.registerCallback(this);
399 //Initialize the speakers
400 for (SpeakerSmart speakers : speakerSet.values()) {
406 // Run the main loop that will keep checking stuff
409 // Update speakers status (on/off) based on info from phone
410 updateSpeakersStatus();
412 // Check and turn on/off (stream music) through speakers based on its status
413 updateSpeakersAction();
416 Thread.sleep(CHECK_TIME_WAIT_MSEC); // sleep for a tenth of the time
417 } catch (Exception e) {