]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - iot-gateway/lighting-gateway.git/blob - client/AndroidClients/LightingController/src/com/lightingcontroller/zllMain.java
79e050fe692bcaf30f91027a0d6580cab2cb2b70
[iot-gateway/lighting-gateway.git] / client / AndroidClients / LightingController / src / com / lightingcontroller / zllMain.java
1 /**************************************************************************************************
2   Filename:       zllMain.java
3   Revised:        $$
4   Revision:       $$
6   Description:    ZLL UI
8   Copyright (C) {2012} Texas Instruments Incorporated - http://www.ti.com/
11    Redistribution and use in source and binary forms, with or without
12    modification, are permitted provided that the following conditions
13    are met:
15      Redistributions of source code must retain the above copyright
16      notice, this list of conditions and the following disclaimer.
18      Redistributions in binary form must reproduce the above copyright
19      notice, this list of conditions and the following disclaimer in the
20      documentation and/or other materials provided with the
21      distribution.
23      Neither the name of Texas Instruments Incorporated nor the names of
24      its contributors may be used to endorse or promote products derived
25      from this software without specific prior written permission.
27    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 **************************************************************************************************/
40 package com.lightingcontroller;
42 import android.app.Activity;
43 import android.app.ProgressDialog;
44 import android.os.AsyncTask;
45 import android.os.Bundle;
46 import android.util.DisplayMetrics;
47 import android.view.Menu;
48 import android.view.MenuInflater;
49 import android.view.MenuItem;
50 import android.view.View;
51 import android.view.ViewGroup;
52 import android.view.WindowManager;
53 import android.widget.AdapterView;
54 import android.widget.AdapterView.OnItemSelectedListener;
55 import android.widget.ArrayAdapter;
56 import android.widget.EditText;
57 import android.widget.SeekBar;
58 import android.widget.Spinner;
59 import android.content.Context;
60 import android.content.DialogInterface;
61 import android.content.Intent;
62 import android.content.res.Configuration;
63 import android.app.AlertDialog;
65 import java.util.ArrayList;
66 import java.util.List; 
67 import java.util.Timer;
68 import java.util.TimerTask;
69 import java.util.concurrent.TimeUnit;
72 import com.lightingcontroller.Zigbee.ZigbeeAssistant;
73 import com.lightingcontroller.Zigbee.ZigbeeDevice;
74 import com.lightingcontroller.Zigbee.ZigbeeGroup;
75 import com.lightingcontroller.ColourPicker;
77 public class zllMain extends Activity {
78     /** Called when the activity is first created. */   
79  
80         
81         public static ColourPicker colourPicker;
82         private static ZigbeeGroup currGroup;   
83         private static ZigbeeDevice currDevice;
84         private Spinner deviceSpinner;
85         private ArrayAdapter<String> deviceSpinnerAdapter;
86         private int currentDeviceSpinnerSelection=0;    
87         
88         ProgressDialog bar;     
89         
90     @Override
91      public void onCreate(Bundle savedInstanceState) {
92         
93         super.onCreate(savedInstanceState);
95         DisplayMetrics metrics = new DisplayMetrics();
96                 WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
97                 wm.getDefaultDisplay().getMetrics(metrics);             
98                 
99         if(metrics.widthPixels > metrics.heightPixels)
100         {
101                 setContentView(R.layout.zllmain);  
102         }
103         else
104         {
105                 setContentView(R.layout.zllmainportraite);              
106         }
107                         
108         setContentView(R.layout.zllmain);
109         
110         colourPicker = (ColourPicker)findViewById(R.id.colourPick);     
112         SeekBar levelControl = (SeekBar)findViewById(R.id.seekBarLevel);
113         levelControl.setMax(0xFF);
114         
115         levelControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
117                    @Override
118                    public void onStopTrackingTouch(SeekBar arg0) {
119                     // TODO Auto-generated method stub
120         
121                    }
122         
123                    @Override
124                    public void onStartTrackingTouch(SeekBar arg0) {
125                     // TODO Auto-generated method stub
126         
127                    }
129                    @Override
130                    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
131                            sendLevelChange((byte)arg1);
132                    }
133         });
135                 
136                 List<ZigbeeDevice> devList = ZigbeeAssistant.getSwitchable();
137         List<String> devNameList = new ArrayList<String>();
138         for (int i = 0 ; i < devList.size() ; i++)
139         {
140                 devNameList.add(devList.get(i).Name);        
141         }                 
142         deviceSpinner = (Spinner) findViewById(R.id.deviceSpinner);
143         deviceSpinnerAdapter = new ArrayAdapter<String>(this,
144                         android.R.layout.simple_spinner_item, devNameList);
145         deviceSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
146         deviceSpinner.setAdapter(deviceSpinnerAdapter);
147         
148         addItemsOnDeviceSpinner();
149         addListenerOnDeviceSpinnerItemSelection();         
150     }    
152     // add items into spinner dynamically
153     public void addItemsOnDeviceSpinner() {  
154         //add devices
155         List<ZigbeeDevice> devList = ZigbeeAssistant.getSwitchable();
156         List<ZigbeeGroup> groupList = ZigbeeAssistant.getGroups(); 
157         deviceSpinnerAdapter.clear();
158         for (int i = 0 ; i < devList.size() ; i++)
159         {               
160                 deviceSpinnerAdapter.add(devList.get(i).Name);
161         }
162         
163         //add groups
164         for (int i = 0 ; i < groupList.size() ; i++)
165         {               
166                 deviceSpinnerAdapter.add("group: " + groupList.get(i).getGroupName());
167         }        
168     }
169    
170     public void addListenerOnDeviceSpinnerItemSelection() {     
171         deviceSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
172             @Override
173             public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
174                 List<ZigbeeDevice> devList = ZigbeeAssistant.getSwitchable();
175                 List<ZigbeeGroup> groupList = ZigbeeAssistant.getGroups();                              
176                 currentDeviceSpinnerSelection = position;
178                 if(currentDeviceSpinnerSelection < devList.size() )
179                 {
180                         currDevice = devList.get(currentDeviceSpinnerSelection);
181                         
182                         currDevice.clearCurrentStateUpdated();
183                         currDevice.clearCurrentLevelUpdated();
184                         currDevice.clearCurrentHueUpdated();
185                         currDevice.clearCurrentSatUpdated();                            
186                         ZigbeeAssistant.getDeviceState(currDevice);                     
187                         ZigbeeAssistant.getDeviceLevel(currDevice);
188                         ZigbeeAssistant.getDeviceHue(currDevice);
189                         ZigbeeAssistant.getDeviceSat(currDevice);
190                         //new waitRspTask().execute("Device Select");   
191                         
192                         currGroup = null;
193                 }
194                 else
195                 {
196                         currDevice = null;
197                         currGroup = groupList.get(currentDeviceSpinnerSelection - devList.size());
198                 }                               
199           }
200          
201           @Override
202           public void onNothingSelected(AdapterView<?> arg0) {
203           }
204         });
205     } 
206         
207     class waitRspTask extends AsyncTask<String , Integer, Void>
208     {
209         private boolean rspSuccess;
210         String param;
211         @Override
212         protected void onPreExecute()
213         {
214             bar = new ProgressDialog(zllMain.this);
215             bar.setMessage("Finding Device");
216             bar.setIndeterminate(true);
217             bar.show();
218         } 
219         @Override
220         protected Void doInBackground(String... params) 
221         {
222                 param = params[0];
223                 
224                 try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) {e.printStackTrace();}
225                 
226             for(int i=0;i<100;i++)
227             {   
228                 if( currDevice.getCurrentStateUpdated() &&
229                                 currDevice.getCurrentLevelUpdated() &&
230                                 currDevice.getCurrentHueUpdated() &&
231                                 currDevice.getCurrentSatUpdated() )
232                 {
233                         colourPicker.upDateColorPreivew( currDevice.getCurrentHue(), currDevice.getCurrentSat() );
234                         //todo change level bar and represent level and state on the color preview
235                         rspSuccess = true;                      
236                         return null;
237                 }
238                 
239                 try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) {e.printStackTrace();}                  
240                 
241                     if( ((i % 30) == 0) && (i > 0) )
242                     {
243                         if( !currDevice.getCurrentStateUpdated() )
244                         {
245                                 ZigbeeAssistant.getDeviceState(currDevice);
246                         }
247                         if(     !currDevice.getCurrentLevelUpdated() )
248                         {
249                                 ZigbeeAssistant.getDeviceLevel(currDevice);
250                         }
251                         if(     !currDevice.getCurrentHueUpdated() )
252                         {                       
253                                 ZigbeeAssistant.getDeviceHue(currDevice);
254                         }
255                         if(     !currDevice.getCurrentSatUpdated() )
256                         {                       
257                                 ZigbeeAssistant.getDeviceSat(currDevice);
258                         }                                       
259                     }
260                             
261             }
262                 
263                 if( currDevice.getCurrentStateUpdated() ||
264                         currDevice.getCurrentLevelUpdated() ||
265                         currDevice.getCurrentHueUpdated() ||
266                         currDevice.getCurrentSatUpdated() )
267                 {
268                         //we got a response but not all HSV value, maybe network is very busy,
269                         //try to handle this gracefully by setting preview to last known values.
270                         colourPicker.upDateColorPreivew( currDevice.getCurrentHue(), currDevice.getCurrentSat() );
271                         //todo change level bar and represent level and state on the color preview
272                         rspSuccess = true;                      
273                         return null;
274                 }
275                 else
276                 {
277                         //We did not get any response, maybe the device is off the network
278                         rspSuccess = false;    
279                         return null;
280                 }
281         }
282         @Override
283         protected void onPostExecute(Void result) 
284         {
285             bar.dismiss();
286             
287             if (rspSuccess == false)
288                 {
289                 AlertDialog show = new AlertDialog.Builder(zllMain.this)
290                         .setTitle(param)
291                         .setMessage("Device " + zllMain.currDevice.Name + " Not Responding.")
292                         .setPositiveButton("OK",             
293                         new DialogInterface.OnClickListener()
294                         {                       
295                                 public void onClick(DialogInterface dialoginterface,int i){                                     
296                                 }               
297                         })                              
298                         .show();
299                 }
300             
301         }
302     }    
304     protected void onResume() {
305         super.onResume();
306         
307                 List<ZigbeeDevice> devList = ZigbeeAssistant.getSwitchable();
308         List<String> devNameList = new ArrayList<String>();
309         for (int i = 0 ; i < devList.size() ; i++)
310         {
311                 devNameList.add(devList.get(i).Name);        
312         }                 
313         deviceSpinner = (Spinner) findViewById(R.id.deviceSpinner);
314         deviceSpinnerAdapter = new ArrayAdapter<String>(this,
315                         android.R.layout.simple_spinner_item, devNameList);
316         deviceSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
317         deviceSpinner.setAdapter(deviceSpinnerAdapter);
318         
319         addItemsOnDeviceSpinner();
320         addListenerOnDeviceSpinnerItemSelection();
321        
322     } 
323     
324     @Override       
325     public void onBackPressed() {    
326         new AlertDialog.Builder(this)
327                 .setTitle("Close")
328                 .setMessage("Are you sure you want to exit?")
329                 .setPositiveButton("OK",          
330                 new DialogInterface.OnClickListener()
331                 {                       
332                         public void onClick(DialogInterface dialoginterface,int i){                                                                     
333                 zllMain.this.finish();                                                                              
334                         }               
335                 })                              
336                 .setNegativeButton("Cancel", null)
337                 .show();                        
338         
339         return;
340     }
341     
342     @Override
343     public boolean onCreateOptionsMenu(Menu menu) {
344         MenuInflater inflater = getMenuInflater();
345         inflater.inflate(R.layout.optionmenu, menu);
346         return true;
347     }  
348     
349     @Override
350     public void onConfigurationChanged(Configuration newConfig) {
351         super.onConfigurationChanged(newConfig);
353         if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
354         {
355                 setContentView(R.layout.zllmain);  
356         }
357         else
358         {
359                 setContentView(R.layout.zllmainportraite);              
360         }
362                 List<ZigbeeDevice> devList = ZigbeeAssistant.getSwitchable();
363         List<String> devNameList = new ArrayList<String>();
364         for (int i = 0 ; i < devList.size() ; i++)
365         {
366                 devNameList.add(devList.get(i).Name);        
367         }                 
368         deviceSpinner = (Spinner) findViewById(R.id.deviceSpinner);
369         deviceSpinnerAdapter = new ArrayAdapter<String>(zllMain.this,
370                         android.R.layout.simple_spinner_item, devNameList);
371         deviceSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
372         deviceSpinner.setAdapter(deviceSpinnerAdapter);
373         
374         addItemsOnDeviceSpinner();
375         addListenerOnDeviceSpinnerItemSelection();      
377     }    
378     
379     public static ZigbeeDevice getCurrentDevice()
380     {
381         return currDevice;      
382     }
384     public boolean onOptionsItemSelected(MenuItem item) {
385         switch (item.getItemId()) {
386             case R.id.optionMenuGroups: 
387                 startActivity(new Intent(zllMain.this, groupSelect.class));
388                 break;                 
389             case R.id.optionMenuScenes: 
390                 startActivity(new Intent(zllMain.this, sceneSelect.class));
391                 break;                
392             case R.id.optionMenuBinding:
393                 startActivity(new Intent(zllMain.this, bindSelect.class));
394                 break;
395             case R.id.optionMenuListDevices:
396             {
397                 AlertDialog alert;
398                         String devicesText = ZigbeeAssistant.getInfoString();  
399                         AlertDialog.Builder builder = new AlertDialog.Builder(this);
400                         builder.setTitle("Zigbee Devices")
401                                    .setMessage(devicesText)
402                                .setCancelable(false)
403                                .setNegativeButton("Okay", new DialogInterface.OnClickListener() {
404                                    public void onClick(DialogInterface dialog, int id) {
405                                            dialog.cancel();
406                                    }
407                                });
408                         alert = builder.create();
409                         alert.show();
410             }                   
411                 break;
412         }
413         return true;
414     }
415  
416     public void deviceChangeNameButton(View view)
417     { 
418         String Title = "Set Name";
419         String Msg = "Please Enter the name of the device";
420         final EditText t = new EditText(this);
422         new AlertDialog.Builder(this)
423                 .setTitle(Title)
424                 .setMessage(Msg)
425                 .setView(t)
426                 .setNegativeButton("CANCEL", null)
427                 .setPositiveButton("OK",             
428                 new DialogInterface.OnClickListener()
429                 {                       
430                         public void onClick(DialogInterface dialoginterface,int i){     
431                         ZigbeeAssistant.setDeviceName( currDevice.Name, t.getText().toString());                
432                         
433                         deviceSpinnerAdapter.clear();
434                         List<ZigbeeDevice> tList = ZigbeeAssistant.getDevices();
435                         for (int j = 0 ; j < tList.size() ; j++)
436                         {
437                                 if (tList.get(j).hasColourable || tList.get(j).hasSwitchable || tList.get(j).hasDimmable)
438                                 {               
439                                         deviceSpinnerAdapter.add(tList.get(j).Name);
440                                 }
441                         }       
442                         
443                         
444                         }               
445                 })
446                 .show();                        
447     }           
448     
449     public void nextPageButton(View view) {  
450         startActivity(new Intent(zllMain.this, sceneSelect.class));     
451         }     
452         
453         public void onCmdButton(View view) {
454                 if(currDevice != null)
455                         ZigbeeAssistant.setDeviceState(currDevice, true);
456                 else if (currGroup != null)
457                 {
458             ZigbeeAssistant.setDeviceState(currGroup, true);
459                 }
460     }
461    
463     public void offCmdButton(View view) {
464                 if(currDevice != null)
465                 {
466                         ZigbeeAssistant.setDeviceState(currDevice, false);
467                 }
468                 else if (currGroup != null)
469                 {
470             ZigbeeAssistant.setDeviceState(currGroup, false);
471                 }
472     }
474     public void tlCmdButton(View view) {
476     }                    
478     public void sendHueSatChange(byte hue, byte sat)
479     {           
480                 if(currDevice != null)    
481                 {
482                         ZigbeeAssistant.setDeviceHueSat(currDevice,hue, sat);
483                 }
484                 else if (currGroup != null)
485                 {
486             ZigbeeAssistant.setDeviceHueSat(currGroup,hue, sat);
487                 }
488     }
489     
490     public void sendLevelChange(byte level)
491     {
492                 if(currDevice != null)          
493                 {
494                         ZigbeeAssistant.setDeviceLevel(currDevice, (char) level);
495                 }
496                 else if (currGroup != null)
497                 {
498             ZigbeeAssistant.setDeviceLevel(currGroup, (char) level);
499                 }       
500     }