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!");
157 // start the speaker playback if the speaker is not playing yet
158 if (!speakers.getPlaybackState()) {
160 System.out.println("Turning a speaker On in room: " + room.getRoomID());
161 speakers.startPlayback();
162 speakers.setPosition(currentPosition);
165 // get average of the positions
166 currPosTotal += speakers.getPosition();
171 //} catch (RemoteException e) {
172 // e.printStackTrace();
176 if (currPosCount != 0) {
178 // get average position of the speakers
179 int currentPosOfSpeakers = (int)(currPosTotal / currPosCount);
181 // check how close we are to the correct position
182 if (Math.abs(currentPosOfSpeakers - currentPosition) > CURRENT_POSITION_SAMPLE_THRESHOLD) {
183 // we were kind of far so update all the positions
185 for (SpeakerSmart speakers : roomSpeakerRel.get(room)) {
187 speakers.setPosition(currentPosOfSpeakers);
188 //} catch (RemoteException e) {
189 // e.printStackTrace();
194 // update the current position
195 currentPosition = currentPosOfSpeakers;
201 // Room status is "off"
203 // used to get the average of the speakers position
204 long currPosTotal = 0;
205 long currPosCount = 0;
207 // Get the speaker objects one by one assuming that we could have
208 // more than one speaker per room
209 for (Speaker speakers : roomSpeakerRel.get(room)) {
210 // System.out.println("DEBUG: Turn off speaker!");
212 // Turning off speaker if they are still on
213 if (speakers.getPlaybackState()) {
214 System.out.println("Turning a speaker off");
216 currPosTotal += (long)speakers.getPosition();
218 boolean tmp = speakers.stopPlayback();
221 System.out.println("Error Turning off");
225 } catch (RemoteException e) {
230 // get the average current position of the speakers
231 // so we can resume other speakers from same position
232 if (currPosCount != 0) {
233 currentPosition = (int)(currPosTotal / currPosCount);
238 // a speaker has finished playing and so we should change all the audio buffers
239 if (playbackDone.get()) {
241 // song done so update the audio buffers
243 playbackDone.set(false);
249 * Update speakers status based on room ID and ring status information from phone
251 private void updateSpeakersStatus() {
253 // If we have new data, we update the speaker streaming
254 if (newDataAvailable.get()) {
256 // System.out.println("DEBUG: New data is available!!!");
257 // System.out.println("DEBUG: Ring status: " + ringStatus);
258 // Check for ring status first
261 // Turn off all speakers if ring status is true (phone is ringing)
262 for (RoomSmart room : audioRooms.values()) {
264 // System.out.println("DEBUG: Update status off for speakers! Phone is ringing!!!");
266 roomSpeakersOnOffStatus.put(room, false);
270 // Phone is not ringing... just play music on the right speaker
272 // Check for every room
273 for (RoomSmart room : audioRooms.values()) {
276 // Turn on the right speaker based on room ID sent from phone app
277 // Stream audio to a speaker based on room ID
278 if (room.getRoomID() == roomIdentifier) {
280 // System.out.println("DEBUG: This room ID: " + room.getRoomID());
281 // System.out.println("DEBUG: Turn on the speaker(s) in this room!!!");
282 // Set speaker status to on
283 roomSpeakersOnOffStatus.put(room, true);
286 // for the rooms whose IDs aren't equal to roomIdentifier
288 // System.out.println("DEBUG: Turn on speaker!");
289 // Set speaker status to off
290 roomSpeakersOnOffStatus.put(room, false);
293 //} catch (RemoteException ex) {
294 // ex.printStackTrace();
298 // Finish processing data - put this back to false
299 newDataAvailable.set(false);
304 * Prepare the speakers for a new song to start playing
306 private void prepareNextSong() {
307 System.out.println("Starting Music Prep");
309 System.out.println("Stopping all device playback");
310 // stop all devices that are still playing and clear their buffers
311 // they are about to end playback anyways
312 for (SpeakerSmart speakers : speakerSet.values()) {
315 if (speakers.getPlaybackState()) {
316 speakers.stopPlayback();
318 speakers.clearData();
319 } catch (Exception e) {
324 // get the music file names that are in the music files directory
325 File musicFolder = new File(MUSIC_FILE_DIRECTORY);
326 File[] audioFiles = musicFolder.listFiles();
327 List<String> audioFileNames = new ArrayList<String>();
329 // put all names in a list
330 for (int i = 0; i < audioFiles.length; i++) {
331 if (audioFiles[i].isFile()) {
333 audioFileNames.add(audioFiles[i].getCanonicalPath());
334 } catch (Exception ex) {
335 ex.printStackTrace();
340 // pick a random file to play
341 Random rand = new Random(System.nanoTime());
342 String audioFilename = audioFileNames.get(rand.nextInt(audioFileNames.size()));
344 System.out.println("Going to load audio file");
345 System.out.println(audioFilename);
347 // decode the mp3 file
348 System.out.println("Starting Decode");
349 MP3Decoder dec = new MP3Decoder(audioFilename);
350 List<short[]> dat = dec.getDecodedFrames();
351 System.out.println("Ending Decode");
355 // count the number of samples
357 for (short[] d : dat) {
361 // make into a single large buffer for 1 large RMI call
362 short[] compressedArray = new short[count];
364 for (short[] d : dat) {
366 compressedArray[count] = s;
372 System.out.println("Loading Speakers");
373 // send the new data to all the speakers
374 for (SpeakerSmart speakers : speakerSet.values()) {
375 System.out.println("Loading a single speaker with data");
377 speakers.loadData(compressedArray, 0, compressedArray.length);
378 } catch (Exception e) {
381 System.out.println("Done loading a single speaker with data");
384 System.out.println("All Speakers done loading");
390 /********************************************************************************************************
391 ** Public methods, called by the runtime
392 *********************************************************************************************************/
394 /** Initialization method, called by the runtime (effectively the main of the controller)
395 * This method runs a continuous loop and is blocking
397 * @return [void] None;
399 public void init() throws RemoteException, InterruptedException {
401 // Initialize the rooms
402 for (RoomSmart room : audioRooms.values()) {
403 // All rooms start with the speakers turned off
404 roomSpeakersOnOffStatus.put(room, false);
407 // Setup the cameras, start them all and assign each one a motion detector
408 for (GPSGatewaySmart gw : gpsSet.values()) {
411 // initialize, register callback, and start the gateway
413 gw.registerCallback(this);
415 //} catch (RemoteException ex) {
416 // ex.printStackTrace();
421 //Initialize the speakers
422 for (SpeakerSmart speakers : speakerSet.values()) {
428 // Run the main loop that will keep checking stuff
431 // Update speakers status (on/off) based on info from phone
432 updateSpeakersStatus();
434 // Check and turn on/off (stream music) through speakers based on its status
435 updateSpeakersAction();
438 Thread.sleep(CHECK_TIME_WAIT_MSEC); // sleep for a tenth of the time
439 } catch (Exception e) {