You are here
Home > RFDuino

Pilot vocally the house lights with RFDuino

We see an Android solution integrated with RFDuino that lets you control with your smartphone and via Bluetooth Low Energy protocol the electrical systems of home and beyond. Powered by electric current alone.

RfDuino is a Bluetooth 4 Low Energy RF Module with ARM Cortex M0 controller and shields.

More dettails on :

http://www.rfduino.com/shop/index.html

 

For the app i use the following electronic components :

  • RFDuino LE Bluetooth RF Module
  • Relay Shield for RFduino; alternatively, to drive relay, you can use scheme below:

image001

 

  • passive and active components to manage power supply and control of OpenJumper Ralays

IMG_20141007_083816 - Copia

  • current sensors ACS712ELC-20A Range. See below:

IMG_20141007_083841 - Copia

Features of App:
I. Direct control of the electrical systems on your smartphone with notification of turn on and off
II. Piloting of the electrical systems on smartphones via voice commands
III. Ability to view at runtime power consumption of each device
IV. Managing voice settings to associate vocal alias name to the physical device and the voice command on or off

Schema

SpeechSwitch_schema

 

IMG_20141007_083752

 

IMG_20141007_083752 - Copia

Class diagram of Android Solution

class2

 

Manifest

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
 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lombamarc.speechswitch"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="18" />
 
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.INTERNET" />
 
    <uses-feature
        android:name="android.hardware.bluetooth_le"
        android:required="true" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.lombamarc.speechswitch.activity.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
        <activity  android:name="com.lombamarc.speechswitch.activity.AboutActivity"  android:label="@string/app_name" />
 
        <activity  android:name="com.lombamarc.speechswitch.activity.RegisterVoiceCommandsActivity" android:label="@string/app_name" />
 
        <activity  android:name="com.lombamarc.speechswitch.activity.RelayDoCommandsActivity" android:label="@string/app_name" />
 
        <activity  android:name="com.lombamarc.speechswitch.activity.EnergyMngActivity"  android:label="@string/app_name" />
 
 
        <service android:name="com.lombamarc.speechswitch.rfduino.RFduinoService" />
    </application>
 
</manifest>

Description of the main classes

MainActivity class ==> This is the entry point of the App :

 

Screenshot_2014-10-06-20-06-10

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
package com.lombamarc.speechswitch.activity;
 
import com.lombamarc.speechswitch.R;
 
import android.app.Activity;
import android.content.Intent;
 
import android.os.Bundle;
 
import android.view.View;
 
import android.widget.Button;
 
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
	private static final String TAG = "Home";
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
 
		super.onCreate(savedInstanceState);
 
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_tabs);
 
			Button btnRegCom = (Button) findViewById(R.id.btnRegCom);
			btnRegCom.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
 
					Intent myIntent = new Intent(getBaseContext(), RegisterVoiceCommandsActivity.class);
					startActivity(myIntent);
				}
			});
			Button btnRegDev = (Button) findViewById(R.id.btnRegDev);
			btnRegDev.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
 
					Intent myIntent = new Intent(getBaseContext(), RelayDoCommandsActivity.class);
					startActivity(myIntent);
				}
			});
			Button btnDoAct = (Button) findViewById(R.id.btnEnerMng);
			btnDoAct.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
 
					Intent myIntent = new Intent(getBaseContext(), EnergyMngActivity.class);
					startActivity(myIntent);
				}
			});
			Button btnAbout = (Button) findViewById(R.id.btnAbout);
			btnAbout.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
 
					Intent myIntent = new Intent(getBaseContext(), AboutActivity.class);
					startActivity(myIntent);
				}
			});
		} catch (Exception e) {
 
			Toast.makeText(this, "Si è verificato un errore", Toast.LENGTH_SHORT).show();
		}
 
	}
 
}

RegisterVoiceCommandActivity ==> this class manage the persistence of the command to activate the relay with 4 options.

Screenshot_2014-10-06-20-06-27

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
package com.lombamarc.speechswitch.activity;
 
import java.util.HashMap;
 
import com.lombamarc.speechswitch.R;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
 
/**
 * 
 * @author mlombardo
 * 
 */
public class RegisterVoiceCommandsActivity extends Activity implements OnClickListener {
 
	private static final String TAG = "RelayCommandsActivity";
 
	SpeechSwitchContextManager sess;
	EditText onVal;
	EditText offVal;
 
	EditText relay1;
	EditText relay2;
	EditText relay3;
	EditText relay4;
 
	Toast msg;
 
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_regcom);
 
		onVal = (EditText) findViewById(R.id.EdTxtOn);
		offVal = (EditText) findViewById(R.id.EdTxtOff);
		relay1 = (EditText) findViewById(R.id.EdTxtR1);
		relay2 = (EditText) findViewById(R.id.EdTxtR2);
		relay3 = (EditText) findViewById(R.id.EdTxtR3);
		relay4 = (EditText) findViewById(R.id.EdTxtR4);
 
		sess = new SpeechSwitchContextManager(getApplicationContext());
 
		// Set default edit values
 
		String conValText = sess.getPref().getString(SpeechSwitchContextManager.KEY_ON_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultOnValue()));
 
		String conPinText = sess.getPref().getString(SpeechSwitchContextManager.KEY_OFF_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultOffValue()));
 
		String r1Text = sess.getPref().getString(SpeechSwitchContextManager.KEY_R1_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultR1Value()));
 
		String r2Text = sess.getPref().getString(SpeechSwitchContextManager.KEY_R2_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultR2Value()));
 
		String r3Text = sess.getPref().getString(SpeechSwitchContextManager.KEY_R3_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultR3Value()));
 
		String r4Text = sess.getPref().getString(SpeechSwitchContextManager.KEY_R4_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultR4Value()));
 
		onVal.setText(conValText);
		offVal.setText(conPinText);
 
		relay1.setText(r1Text);
		relay2.setText(r2Text);
		relay3.setText(r3Text);
		relay4.setText(r4Text);
 
		//
 
		findViewById(R.id.btnSaveOptions).setOnClickListener(this);
 
	}
 
	@Override
	public void onClick(View view) {
 
		if (view.getId() == R.id.btnSaveOptions) {
 
			String onValText = onVal.getText().toString();
 
			String offValText = offVal.getText().toString();
 
			String r1ValText = relay1.getText().toString();
 
			String r2ValText = relay2.getText().toString();
 
			String r3ValText = relay3.getText().toString();
 
			String r4ValText = relay4.getText().toString();
 
			HashMap<String, String> map = new HashMap();
 
			map.put(SpeechSwitchContextManager.KEY_ON_VALUE, onValText);
 
			map.put(SpeechSwitchContextManager.KEY_OFF_VALUE, offValText);
 
			map.put(SpeechSwitchContextManager.KEY_R1_VALUE, r1ValText);
			map.put(SpeechSwitchContextManager.KEY_R2_VALUE, r2ValText);
			map.put(SpeechSwitchContextManager.KEY_R3_VALUE, r3ValText);
			map.put(SpeechSwitchContextManager.KEY_R4_VALUE, r4ValText);
 
			sess.createPreferenceIstance(map);
 
			finish();
 
		}
 
	}
 
}

RelayDoCommandsActivity ==> this class manage all operative commands : connect to rfduino, listen the command and get results. For speech, I use the google speech recognition services.

Screenshot_2014-10-06-20-06-17

Screenshot_2014-10-06-20-06-21

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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
package com.lombamarc.speechswitch.activity;
 
import android.annotation.SuppressLint;
 
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
 
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
 
import com.lombamarc.speechswitch.R;
import com.lombamarc.speechswitch.rfduino.BluetoothHelper;
import com.lombamarc.speechswitch.rfduino.EditData;
import com.lombamarc.speechswitch.rfduino.HexAsciiHelper;
import com.lombamarc.speechswitch.rfduino.RFduinoService;
import com.lombamarc.speechswitch.rfduino.RFduinoService.LocalBinder;
 
@SuppressLint("NewApi")
public class RelayDoCommandsActivity extends Activity implements BluetoothAdapter.LeScanCallback {
	// State machine
	final private static int STATE_BLUETOOTH_OFF = 1;
	final private static int STATE_DISCONNECTED = 2;
	final private static int STATE_CONNECTING = 3;
	final private static int STATE_CONNECTED = 4;
 
	private static final int REQUEST_CODE = 1234;
	private ListView resultList;
	Button speakButton;
 
	private int state;
 
	private String TAG = "RELAY";
 
	private boolean scanStarted;
	private boolean scanning;
 
	private BluetoothAdapter bluetoothAdapter;
	private BluetoothDevice bluetoothDevice;
 
	private RFduinoService rfduinoService;
 
	private Button enableBluetoothButton;
	private TextView scanStatusText;
	private Button scanButton;
	private TextView deviceInfoText;
	private TextView connectionStatusText;
	private Button connectButton;
 
	// private EditData valueEdit;
	// private Button sendZeroButton;
	// private Button sendValueButton;
	// private Button clearButton;
	// private LinearLayout dataLayout;
 
	private boolean r1Value;
	private boolean r2Value;
	private boolean r3Value;
	private boolean r4Value;
 
	private Button sendR1Button;
	private Button sendR2Button;
	private Button sendR3Button;
	private Button sendR4Button;
 
	private final BroadcastReceiver bluetoothStateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
			if (state == BluetoothAdapter.STATE_ON) {
				upgradeState(STATE_DISCONNECTED);
			} else if (state == BluetoothAdapter.STATE_OFF) {
				downgradeState(STATE_BLUETOOTH_OFF);
			}
		}
	};
 
	private final BroadcastReceiver scanModeReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			scanning = (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_NONE);
			scanStarted &= scanning;
			updateUi();
		}
	};
 
	private final ServiceConnection rfduinoServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			rfduinoService = ((RFduinoService.LocalBinder) service).getService();
			if (rfduinoService.initialize()) {
				if (rfduinoService.connect(bluetoothDevice.getAddress())) {
					upgradeState(STATE_CONNECTING);
				}
			}
		}
 
		@Override
		public void onServiceDisconnected(ComponentName name) {
			rfduinoService = null;
			downgradeState(STATE_DISCONNECTED);
		}
	};
 
	private final BroadcastReceiver rfduinoReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (RFduinoService.ACTION_CONNECTED.equals(action)) {
				upgradeState(STATE_CONNECTED);
			} else if (RFduinoService.ACTION_DISCONNECTED.equals(action)) {
				downgradeState(STATE_DISCONNECTED);
			} else if (RFduinoService.ACTION_DATA_AVAILABLE.equals(action)) {
				updateData(intent.getByteArrayExtra(RFduinoService.EXTRA_DATA));
			}
		}
	};
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_act_relay);
 
		bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 
		// Bluetooth
		enableBluetoothButton = (Button) findViewById(R.id.enableBluetooth);
		enableBluetoothButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				enableBluetoothButton.setEnabled(false);
				enableBluetoothButton.setText(bluetoothAdapter.enable() ? "Enabling bluetooth..." : "Enable failed!");
			}
		});
 
		// Find Device
		scanStatusText = (TextView) findViewById(R.id.scanStatus);
 
		scanButton = (Button) findViewById(R.id.scan);
		scanButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				scanStarted = true;
				bluetoothAdapter.startLeScan(new UUID[] { RFduinoService.UUID_SERVICE }, RelayDoCommandsActivity.this);
			}
		});
 
		// Device Info
		deviceInfoText = (TextView) findViewById(R.id.deviceInfo);
 
		// Connect Device
		connectionStatusText = (TextView) findViewById(R.id.connectionStatus);
 
		connectButton = (Button) findViewById(R.id.connect);
		connectButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				v.setEnabled(false);
				connectionStatusText.setText("Connecting...");
				Intent rfduinoIntent = new Intent(RelayDoCommandsActivity.this, RFduinoService.class);
				bindService(rfduinoIntent, rfduinoServiceConnection, BIND_AUTO_CREATE);
			}
		});
 
		// Send
		/**
		 * valueEdit = (EditData) findViewById(R.id.value);
		 * valueEdit.setImeOptions(EditorInfo.IME_ACTION_SEND);
		 * valueEdit.setOnEditorActionListener(new
		 * TextView.OnEditorActionListener() {
		 * 
		 * @Override public boolean onEditorAction(TextView v, int actionId,
		 *           KeyEvent event) { if (actionId ==
		 *           EditorInfo.IME_ACTION_SEND) {
		 *           sendValueButton.callOnClick(); return true; } return false;
		 *           } });
		 * 
		 *           sendZeroButton = (Button) findViewById(R.id.sendZero);
		 *           sendZeroButton.setOnClickListener(new
		 *           View.OnClickListener() {
		 * @Override public void onClick(View v) { rfduinoService.send(new
		 *           byte[]{0}); } });
		 * 
		 *           sendValueButton = (Button) findViewById(R.id.sendValue);
		 *           sendValueButton.setOnClickListener(new
		 *           View.OnClickListener() {
		 * @Override public void onClick(View v) {
		 *           rfduinoService.send(valueEdit.getData()); } });
		 * 
		 *           // Receive clearButton = (Button)
		 *           findViewById(R.id.clearData);
		 *           clearButton.setOnClickListener(new View.OnClickListener() {
		 * @Override public void onClick(View v) { dataLayout.removeAllViews();
		 *           } });
		 * 
		 *           dataLayout = (LinearLayout) findViewById(R.id.dataLayout);
		 **/
 
		// Relay 1
		sendR1Button = (Button) findViewById(R.id.sendR1);
		sendR1Button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				rfduinoService.send(getRelayPublishMsg(1));
			}
		});
		// Relay 2
		sendR2Button = (Button) findViewById(R.id.sendR2);
		sendR2Button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				rfduinoService.send(getRelayPublishMsg(2));
			}
		});
		// Relay 3
		sendR3Button = (Button) findViewById(R.id.sendR3);
		sendR3Button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				rfduinoService.send(getRelayPublishMsg(3));
			}
		});
		// Relay 4
		sendR4Button = (Button) findViewById(R.id.sendR4);
		sendR4Button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				rfduinoService.send(getRelayPublishMsg(4));
			}
		});
 
		speakButton = (Button) findViewById(R.id.speakButton);
 
		resultList = (ListView) findViewById(R.id.list);
 
		// Disable button if no recognition service is present
		PackageManager pm = getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH),
				0);
		if (activities.size() == 0) {
			speakButton.setEnabled(false);
			Toast.makeText(getApplicationContext(), "Recognizer Not Found", 1000).show();
		}
		speakButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startVoiceRecognitionActivity();
			}
		});
 
	}
 
	private void startVoiceRecognitionActivity() {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
 
		intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
 
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
 
		intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 900);
 
		intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 2500);
 
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech Switch Voice Recognition...");
 
		startActivityForResult(intent, REQUEST_CODE);
	}
 
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
 
			ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
 
			resultList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches));
 
			Log.i(TAG, "" + matches.size());
 
			// Manage first result
 
			String firstMatch = matches.get(0);
 
			Log.i(TAG, "" + firstMatch);
 
			HashMap<String, String> hash = buildDecisionVoiceCommand();
 
			String rfComm = hash.get(firstMatch);
 
			Log.i(TAG, "" + rfComm);
 
			if (rfComm != null)
				rfduinoService.send(rfComm.getBytes());
 
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
 
	private HashMap<String, String> buildDecisionVoiceCommand() {
		HashMap<String, String> hash = new HashMap<String, String>();
		SpeechSwitchContextManager sess = new SpeechSwitchContextManager(getApplicationContext());
 
		// Set default edit values
 
		String onVal = sess.getPref().getString(SpeechSwitchContextManager.KEY_ON_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultOnValue()));
		String offVal = sess.getPref().getString(SpeechSwitchContextManager.KEY_OFF_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultOffValue()));
		String r1Val = sess.getPref().getString(SpeechSwitchContextManager.KEY_R1_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultR1Value()));
		String r2Val = sess.getPref().getString(SpeechSwitchContextManager.KEY_R2_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultR2Value()));
		String r3Val = sess.getPref().getString(SpeechSwitchContextManager.KEY_R3_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultR3Value()));
		String r4Val = sess.getPref().getString(SpeechSwitchContextManager.KEY_R4_VALUE,
				String.valueOf(SpeechSwitchContextManager.defaultR4Value()));
 
		hash.put(r1Val + " " + onVal, "11");
		hash.put(r2Val + " " + onVal, "21");
		hash.put(r3Val + " " + onVal, "31");
		hash.put(r4Val + " " + onVal, "41");
 
		hash.put(r1Val + " " + offVal, "10");
		hash.put(r2Val + " " + offVal, "20");
		hash.put(r3Val + " " + offVal, "30");
		hash.put(r4Val + " " + offVal, "40");
 
		return hash;
 
	}
 
	private byte[] getRelayPublishMsg(int relayId) {
		byte[] msg = null;
 
		Class<?> c = this.getClass();
 
		Field rVal;
		try {
 
			rVal = c.getDeclaredField("r" + relayId + "Value");
			Boolean value = rVal.getBoolean(this);
			boolean newValue = !value.booleanValue();
 
			msg = ("" + relayId + (newValue ? '1' : '0')).getBytes();
 
		} catch (NoSuchFieldException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
 
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
		return msg;
 
	}
 
	@Override
	protected void onStart() {
		super.onStart();
 
		registerReceiver(scanModeReceiver, new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));
		registerReceiver(bluetoothStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
		registerReceiver(rfduinoReceiver, RFduinoService.getIntentFilter());
 
		updateState(bluetoothAdapter.isEnabled() ? STATE_DISCONNECTED : STATE_BLUETOOTH_OFF);
	}
 
	@Override
	protected void onStop() {
		super.onStop();
 
		bluetoothAdapter.stopLeScan(this);
 
		unregisterReceiver(scanModeReceiver);
		unregisterReceiver(bluetoothStateReceiver);
		unregisterReceiver(rfduinoReceiver);
	}
 
	private void upgradeState(int newState) {
		if (newState > state) {
			updateState(newState);
		}
	}
 
	private void downgradeState(int newState) {
		if (newState < state) {
			updateState(newState);
		}
	}
 
	private void updateState(int newState) {
		state = newState;
		updateUi();
	}
 
	private void updateUi() {
		// Enable Bluetooth
		boolean on = state > STATE_BLUETOOTH_OFF;
		enableBluetoothButton.setEnabled(!on);
		enableBluetoothButton.setText(on ? "Bluetooth enabled" : "Enable Bluetooth");
		scanButton.setEnabled(on);
 
		// Scan
		if (scanStarted && scanning) {
			scanStatusText.setText("Scanning...");
			scanButton.setText("Stop Scan");
			scanButton.setEnabled(true);
		} else if (scanStarted) {
			scanStatusText.setText("Scan started...");
			scanButton.setEnabled(false);
		} else {
			scanStatusText.setText("");
			scanButton.setText("Scan");
			scanButton.setEnabled(true);
		}
 
		// Connect
		boolean connected = false;
		String connectionText = "Disconnected";
		if (state == STATE_CONNECTING) {
			connectionText = "Connecting...";
		} else if (state == STATE_CONNECTED) {
			connected = true;
			connectionText = "Connected";
		}
		connectionStatusText.setText(connectionText);
		connectButton.setEnabled(bluetoothDevice != null && state == STATE_DISCONNECTED);
 
		// Send
		// sendZeroButton.setEnabled(connected);
		// sendValueButton.setEnabled(connected);
 
		sendR1Button.setEnabled(connected);
		sendR2Button.setEnabled(connected);
		sendR3Button.setEnabled(connected);
		sendR4Button.setEnabled(connected);
 
	}
 
	/**
	 * private void addData(byte[] data) { View view =
	 * getLayoutInflater().inflate(android.R.layout.simple_list_item_2,
	 * dataLayout, false);
	 * 
	 * TextView text1 = (TextView) view.findViewById(android.R.id.text1);
	 * text1.setText(HexAsciiHelper.bytesToHex(data));
	 * 
	 * String ascii = HexAsciiHelper.bytesToAsciiMaybe(data); if (ascii != null)
	 * { TextView text2 = (TextView) view.findViewById(android.R.id.text2);
	 * text2.setText(ascii); }
	 * 
	 * dataLayout.addView( view, LinearLayout.LayoutParams.MATCH_PARENT,
	 * LinearLayout.LayoutParams.WRAP_CONTENT); }
	 **/
 
	private void setBackGroundButton(boolean on_off, Button button) {
		if (on_off)
			button.setBackground(getResources().getDrawable(R.layout.gradient_on));
		else
			button.setBackground(getResources().getDrawable(R.layout.gradient_off));
	}
 
	private void updateData(byte[] data) {
 
		String ascii = HexAsciiHelper.bytesToAsciiMaybe(data);
		if (ascii != null && ascii.length() >= 2) {
 
			char relayID = ascii.charAt(0);
			char relayVal = ascii.charAt(1);
 
			switch (relayID) {
			case 'A':
 
				if (relayVal == '1' && !this.r1Value) {
					this.r1Value = true;
 
					// sendR1Button.setBackgroundColor(Color.GREEN);
					setBackGroundButton(true, sendR1Button);
 
				} else if (relayVal == '0' && this.r1Value) {
					this.r1Value = false;
 
					// sendR1Button.setBackgroundColor(Color.RED);
					setBackGroundButton(false, sendR1Button);
				}
 
				break;
			case 'B':
				if (relayVal == '1' && !this.r2Value) {
					this.r2Value = true;
 
					// sendR2Button.setBackgroundColor(Color.GREEN);
					setBackGroundButton(true, sendR2Button);
 
				} else if (relayVal == '0' && this.r2Value) {
					this.r2Value = false;
 
					// sendR2Button.setBackgroundColor(Color.RED);
					setBackGroundButton(false, sendR2Button);
				}
				break;
			case 'C':
				if (relayVal == '1' && !this.r3Value) {
					this.r3Value = true;
 
					// sendR3Button.setBackgroundColor(Color.GREEN);
					setBackGroundButton(true, sendR3Button);
 
				} else if (relayVal == '0' && this.r3Value) {
					this.r3Value = false;
 
					// sendR3Button.setBackgroundColor(Color.RED);
					setBackGroundButton(false, sendR3Button);
				}
				break;
			case 'D':
				if (relayVal == '1' && !this.r4Value) {
					this.r4Value = true;
 
					// sendR4Button.setBackgroundColor(Color.GREEN);
					setBackGroundButton(true, sendR4Button);
 
				} else if (relayVal == '0' && this.r4Value) {
					this.r4Value = false;
 
					// sendR4Button.setBackgroundColor(Color.RED);
					setBackGroundButton(false, sendR4Button);
				}
				break;
 
			default:
				break;
			}
 
		}
 
	}
 
	@Override
	public void onLeScan(BluetoothDevice device, final int rssi, final byte[] scanRecord) {
		bluetoothAdapter.stopLeScan(this);
		bluetoothDevice = device;
 
		RelayDoCommandsActivity.this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				deviceInfoText.setText(BluetoothHelper.getDeviceInfoText(bluetoothDevice, rssi, scanRecord));
				updateUi();
			}
		});
	}
 
}

Sketch to upload in RFDuino

#include <RFduinoBLE.h>

// Mapping relays to pin of board (OUT)

int r1 = 3;

int r2 = 4;

int r3 = 5;

int r4 = 6;

char *command;

int isCo = 0;

//MApping current sensors (IN)

int CURRENT_SENSOR0= 1;

int CURRENT_SENSOR1= 2;

int CURRENT_SENSOR2= 0;

// Europe voltage to 230V

float effective_voltage = 230;

//fields for power elaboration

float amplitude_current0;

float effective_value0;

float effective_power0;

float zero_sensor0;

float amplitude_current1;

float effective_value1;

float effective_power1;

float zero_sensor1;

float amplitude_current2;

float effective_value2;

float effective_power2;

float zero_sensor2;

void setup() {

Serial.begin(9600);

//RELAY OUT

pinMode(r1, OUTPUT);

pinMode(r2, OUTPUT);

pinMode(r3, OUTPUT);

pinMode(r4, OUTPUT);

//Current sensors IN

pinMode(CURRENT_SENSOR0, INPUT);

pinMode(CURRENT_SENSOR1, INPUT);

pinMode(CURRENT_SENSOR2, INPUT);

digitalWrite(r1, LOW);

digitalWrite(r2, LOW);

digitalWrite(r3, LOW);

digitalWrite(r4, LOW);

// Calibrate sensor with null current

zero_sensor0 = getSensorValue(CURRENT_SENSOR0);

zero_sensor1 = getSensorValue(CURRENT_SENSOR1);

zero_sensor2 = getSensorValue(CURRENT_SENSOR2);

RFduinoBLE.advertisementData = “swpbtn“;

// start the BLE stack

RFduinoBLE.begin();

}

void loop() {

if (strncmp(command, “A1”, 2) == 0)

updatePinValue(r1, HIGH);

else if (strncmp(command, “A0”, 2) == 0)

updatePinValue(r1, LOW);

else if (strncmp(command, “B1”, 2) == 0)

updatePinValue(r2, HIGH);

else if (strncmp(command, “B0”, 2) == 0)

updatePinValue(r2, LOW);

else if (strncmp(command, “C1”, 2) == 0)

updatePinValue(r3, HIGH);

else if (strncmp(command, “C0”, 2) == 0)

updatePinValue(r3, LOW);

else if (strncmp(command, “D1”, 2) == 0)

updatePinValue(r4, HIGH);

else if (strncmp(command, “D0”, 2) == 0)

updatePinValue(r4, LOW);

Serial.println(command);

//Energy Mng

// Perform power measurement

float sensor_value0 = getSensorValue(CURRENT_SENSOR0);

float sensor_value1 = getSensorValue(CURRENT_SENSOR1);

float sensor_value2 = getSensorValue(CURRENT_SENSOR2);

// Convert to current 0

amplitude_current0=getAmplitudeCurrent(sensor_value0, zero_sensor0);

amplitude_current1=getAmplitudeCurrent(sensor_value1, zero_sensor1);

amplitude_current2=getAmplitudeCurrent(sensor_value2, zero_sensor2);

float effective_power0= getEffectivePower (amplitude_current0);

float effective_power1= getEffectivePower (amplitude_current1);

float effective_power2= getEffectivePower (amplitude_current2);

serialTracePower(amplitude_current0, effective_power0);

serialTracePower(amplitude_current1, effective_power1);

serialTracePower(amplitude_current2, effective_power2);

sendEnergyValue2Device(“A”, effective_power0);

sendEnergyValue2Device(“B”, effective_power1);

sendEnergyValue2Device(“C”, effective_power2);

delay(20);

}

//Elaborate Current in [mA]

float getAmplitudeCurrent(float _sensor_value, float _zero_sensor)

{

float _amplitude_current=(float)(_sensor_value-_zero_sensor)/1024*3/100*1000000;

return _amplitude_current;

}

//Elaborate Power in [W]

float getEffectivePower (float _amplitude_current)

{

float _effective_value=_amplitude_current/1.414;

float _effective_power=abs(_effective_value*effective_voltage/1000);

return _effective_power;

}

void serialTracePower(float _amplitude_current, float _effective_power)

{

Serial.println(“Current amplitude (in mA): “);

Serial.println(_amplitude_current,1);

Serial.println(“Current effective value (in mA)”);

Serial.println(effective_value1,1);

Serial.println(“Effective power (in W): “);

Serial.println(_effective_power,1);

Serial.println(“”);

}

void sendEnergyValue2Device(char* idRelay, float _effective_power)

{

String s1_post=String((int)_effective_power);

Serial.print(“send value send for …”);

Serial.println(idRelay);

Serial.println(“IS”);

Serial.println(s1_post);

int l1=s1_post.length();

char* tosend1=new char[l1];

for (unsigned i=0; i<s1_post.length(); ++i)

{tosend1[i]= s1_post.charAt(i);}

RFduinoBLE.send(idRelay ,1);

RFduinoBLE.send(tosend1,strlen(tosend1));

delay (10);

}

float getSensorValue(int _sensorpin)

{

int sensorValue;

float avgSensor = 0;

int nb_measurements = 100;

for (int i = 0; i < nb_measurements; i++) {

sensorValue = analogRead(_sensorpin);

avgSensor = avgSensor + float(sensorValue);

}

avgSensor = avgSensor/float(nb_measurements);

return avgSensor;

}

void RFduinoBLE_onReceive(char *data, int len)

{

Serial.println(data[0]);

Serial.println(data[1]);

// first byte ==> relè ; second byte ==> on/off

if (data[0]==’1′ && data[1]==’1′)

command=”A1″;

else if (data[0]==’1′ && data[1]==’0′)

command=”A0″;

else if (data[0]==’2′ && data[1]==’1′)

command=”B1″;

else if (data[0]==’2′ && data[1]==’0′)

command=”B0″;

else if (data[0]==’3′ && data[1]==’1′)

command=”C1″;

else if (data[0]==’3′ && data[1]==’0′)

command=”C0″;

else if (data[0]==’4′ && data[1]==’1′)

command=”D1″;

else if (data[0]==’4′ && data[1]==’0′)

command=”D0″;

}

void updatePinValue(int rPin, boolean rVal)

{

digitalWrite(rPin, rVal);

delay(100);

RFduinoBLE.send(command,2);

}

void RFduinoBLE_onConnect() {

isCo = 1;

}

void RFduinoBLE_onDisconnect() {

isCo = 0;

}

The video below shows how work the app.

 

lombamarc
I have over ten years experience in project management and software architect in complex and innovative projects for multinational ICT. I have a electronic engineer extraction with automatic specialization. For years I deal with innovation also as an active contributor to several open hardware community as Rfduino, Arduino Yun, etc ... I think that in every company there is a need to co-create ideas and innovation from every person with tools and working groups motivated and sharing and dissemination of culture at all levels. Technology and research are not enough, if there is no interaction and sharing there can be no innovation.

Leave a Reply

Top