├── examples
├── ic_launcher-web.png
├── res
│ ├── drawable-xhdpi
│ │ └── ic_launcher.png
│ ├── values-sw600dp
│ │ └── dimens.xml
│ ├── values
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ ├── menu
│ │ └── sample.xml
│ ├── values-sw720dp-land
│ │ └── dimens.xml
│ ├── values-v11
│ │ └── styles.xml
│ ├── values-v14
│ │ └── styles.xml
│ └── layout
│ │ ├── lifx_list_item_layout.xml
│ │ ├── lifx_main_activity_layout.xml
│ │ └── lifx_list_sample_layout.xml
├── project.properties
├── proguard-project.txt
├── src
│ └── com
│ │ └── example
│ │ └── lifx_sdk_samples
│ │ ├── LFXSDKLightListAdapter.java
│ │ ├── LFXSDKTaggedLightCollectionListAdapter.java
│ │ ├── LFXSDKSamplesActivity.java
│ │ ├── LFXSDKLightRandomColorActivity.java
│ │ ├── LFXSDKLightPowerActivity.java
│ │ └── LFXSDKLightEditLabelActivity.java
└── AndroidManifest.xml
├── library
├── AndroidManifest.xml
├── src
│ └── lifx
│ │ └── java
│ │ └── android
│ │ ├── network_context
│ │ └── internal
│ │ │ ├── transport_manager
│ │ │ ├── gateway_connection
│ │ │ │ ├── LFXTCPGatewayConnection.java
│ │ │ │ ├── LFXGatewayConnection.java
│ │ │ │ ├── LFXSocketUDP.java
│ │ │ │ ├── LFXSocketTCP.java
│ │ │ │ ├── LFXSocketGeneric.java
│ │ │ │ └── LFXUDPGatewayConnection.java
│ │ │ ├── lan
│ │ │ │ ├── gateway_discovery
│ │ │ │ │ ├── LFXGatewayDiscoveryTableEntry.java
│ │ │ │ │ └── LFXGatewayDiscoveryController.java
│ │ │ │ └── LFXLANTransportManager.java
│ │ │ └── LFXTransportManager.java
│ │ │ └── routing_table
│ │ │ └── LFXRoutingTable.java
│ │ ├── constant
│ │ └── LFXSDKConstants.java
│ │ ├── entities
│ │ ├── LFXTypes.java
│ │ ├── internal
│ │ │ ├── LFXDeviceMapping.java
│ │ │ ├── LFXTagMapping.java
│ │ │ ├── LFXMessageObservationDescriptor.java
│ │ │ ├── LFXSiteID.java
│ │ │ ├── LFXBinaryPath.java
│ │ │ ├── LFXBinaryTypes.java
│ │ │ ├── LFXTarget.java
│ │ │ ├── LFXGatewayDescriptor.java
│ │ │ ├── LFXBinaryTargetID.java
│ │ │ └── structle
│ │ │ │ └── LxProtocolSensor.java
│ │ ├── LFXLightTarget.java
│ │ └── LFXHSBKColor.java
│ │ ├── util
│ │ ├── LFXLog.java
│ │ ├── LFXTimerUtils.java
│ │ ├── LFXByteUtils.java
│ │ └── LFXNetworkUtils.java
│ │ ├── client
│ │ └── LFXClient.java
│ │ ├── light
│ │ ├── internal
│ │ │ └── LFXAllLightsCollection.java
│ │ ├── LFXTaggedLightCollection.java
│ │ ├── LFXLightCollection.java
│ │ └── LFXLight.java
│ │ └── internal
│ │ └── LFXWiFiObserver.java
├── project.properties
└── proguard-project.txt
├── .gitignore
├── README.md
└── LICENSE
/examples/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LIFX/lifx-sdk-android/HEAD/examples/ic_launcher-web.png
--------------------------------------------------------------------------------
/examples/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LIFX/lifx-sdk-android/HEAD/examples/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/examples/res/values-sw600dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/examples/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 16dp
5 | 16dp
6 |
7 |
8 |
--------------------------------------------------------------------------------
/examples/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | LIFX_SDK_SAMPLES
5 | Settings
6 | Hello world!
7 |
8 |
9 |
--------------------------------------------------------------------------------
/examples/res/menu/sample.xml:
--------------------------------------------------------------------------------
1 |
10 |
--------------------------------------------------------------------------------
/examples/res/values-sw720dp-land/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 | 128dp
8 |
9 |
10 |
--------------------------------------------------------------------------------
/examples/res/values-v11/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/library/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
9 |
10 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .project
3 | .classpath
4 | .settings
5 | .checkstyle
6 |
7 | # IntelliJ IDEA
8 | .idea
9 | *.iml
10 | *.ipr
11 | *.iws
12 | classes
13 | gen-external-apklibs
14 |
15 | # Gradle
16 | .gradle
17 | build
18 |
19 | # Maven
20 | target
21 | release.properties
22 | pom.xml.*
23 |
24 | # Ant
25 | bin
26 | gen
27 | build.xml
28 | ant.properties
29 | local.properties
30 | proguard.cfg
31 | proguard-project.txt
32 |
33 | # Other
34 | .DS_Store
--------------------------------------------------------------------------------
/examples/res/values-v14/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/transport_manager/gateway_connection/LFXTCPGatewayConnection.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXTCPGatewayConnection.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.transport_manager.gateway_connection;
10 |
11 | public class LFXTCPGatewayConnection {
12 | private final static String TAG = LFXTCPGatewayConnection.class.getSimpleName();
13 | }
14 |
--------------------------------------------------------------------------------
/library/project.properties:
--------------------------------------------------------------------------------
1 | # This file is automatically generated by Android Tools.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must be checked in Version Control Systems.
5 | #
6 | # To customize properties used by the Ant build system edit
7 | # "ant.properties", and override values to adapt the script to your
8 | # project structure.
9 | #
10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
12 |
13 | # Project target.
14 | target=android-19
15 | android.library=true
16 |
--------------------------------------------------------------------------------
/examples/project.properties:
--------------------------------------------------------------------------------
1 | # This file is automatically generated by Android Tools.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must be checked in Version Control Systems.
5 | #
6 | # To customize properties used by the Ant build system edit
7 | # "ant.properties", and override values to adapt the script to your
8 | # project structure.
9 | #
10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
12 |
13 | # Project target.
14 | target=android-19
15 | android.library.reference.1=../LIFX_SDK
16 |
--------------------------------------------------------------------------------
/examples/res/layout/lifx_list_item_layout.xml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
16 |
17 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/examples/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
14 |
15 |
16 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/constant/LFXSDKConstants.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSDKConstants.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.constant;
10 |
11 | public class LFXSDKConstants {
12 | public static final long LFX_UDP_MESSAGE_SEND_RATE_LIMIT_INTERVAL = 200;
13 | public static final long LFX_UDP_HEARTBEAT_INTERVAL = 15000;
14 | public static final long LFX_UDP_IDLE_TIMEOUT_INTERVAL = 20000;
15 |
16 | public static final long LFX_TCP_MESSAGE_SEND_RATE_LIMIT_INTERVAL = 200;
17 | public static final long LFX_TCP_HEARTBEAT_INTERVAL = 15000;
18 | public static final long LFX_TCP_IDLE_TIMEOUT_INTERVAL = 20000;
19 |
20 | public static final long LFX_SITE_SCAN_TIMER_INTERVAL = 30000;
21 | }
22 |
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # LIFX
2 |
3 | LIFX will no longer be supporting lifx-sdk-android. This has been done in order to better support developers by focusing instead on releasing documentation for the LAN protocol itself and enabling SDKs to be produced in any language. We have also published a HTTP API cloud-based light control from anywhere.
4 |
5 | Our Developer Zone is available if you have any questions about using the newly released documentation. You can find it at https://community.lifx.com/
6 |
7 | We sincerely hope that someone decides to fork this repository and continues maintaining it. If you do this please feel free to let us know on the Developer Zone or by email at developers@lifx.com. We will do our best to support your efforts.
8 |
9 | We hope that our new commitment to support public documentation allows better quality libraries than we have the resources to support alone.
10 |
--------------------------------------------------------------------------------
/examples/proguard-project.txt:
--------------------------------------------------------------------------------
1 | # To enable ProGuard in your project, edit project.properties
2 | # to define the proguard.config property as described in that file.
3 | #
4 | # Add project specific ProGuard rules here.
5 | # By default, the flags in this file are appended to flags specified
6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 | # You can edit the include path and order by changing the ProGuard
8 | # include property in project.properties.
9 | #
10 | # For more details, see
11 | # http://developer.android.com/guide/developing/tools/proguard.html
12 |
13 | # Add any project specific keep options here:
14 |
15 | # If your project uses WebView with JS, uncomment the following
16 | # and specify the fully qualified class name to the JavaScript interface
17 | # class:
18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 | # public *;
20 | #}
21 |
--------------------------------------------------------------------------------
/library/proguard-project.txt:
--------------------------------------------------------------------------------
1 | # To enable ProGuard in your project, edit project.properties
2 | # to define the proguard.config property as described in that file.
3 | #
4 | # Add project specific ProGuard rules here.
5 | # By default, the flags in this file are appended to flags specified
6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 | # You can edit the include path and order by changing the ProGuard
8 | # include property in project.properties.
9 | #
10 | # For more details, see
11 | # http://developer.android.com/guide/developing/tools/proguard.html
12 |
13 | # Add any project specific keep options here:
14 |
15 | # If your project uses WebView with JS, uncomment the following
16 | # and specify the fully qualified class name to the JavaScript interface
17 | # class:
18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 | # public *;
20 | #}
21 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/LFXTypes.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXTypes.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities;
10 |
11 | public class LFXTypes {
12 | public enum LFXDeviceReachability {
13 | REACHABLE,
14 | UNREACHABLE,
15 | }
16 |
17 | public enum LFXFuzzyPowerState {
18 | OFF,
19 | ON,
20 | MIXED,
21 | }
22 |
23 | public enum LFXPowerState {
24 | ON,
25 | OFF,
26 | }
27 |
28 | public static LFXFuzzyPowerState getLFXFuzzyPowerStateFromPowerState(LFXPowerState powerState) {
29 | switch (powerState) {
30 | case OFF:
31 | return LFXFuzzyPowerState.OFF;
32 | case ON:
33 | return LFXFuzzyPowerState.ON;
34 | }
35 | return LFXFuzzyPowerState.OFF;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/util/LFXLog.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXLog.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.util;
10 |
11 | import android.util.Log;
12 |
13 | public class LFXLog {
14 | private static boolean info = true;
15 | private static boolean error = true;
16 | private static boolean warning = true;
17 | private static boolean verbose = true;
18 | private static boolean debug = true;
19 |
20 | public static void i(String tag, String input) {
21 | if (info) Log.i(tag, input);
22 | }
23 |
24 | public static void e(String tag, String input) {
25 | if (error) Log.e(tag, input);
26 | }
27 |
28 | public static void w(String tag, String input) {
29 | if (warning) Log.w(tag, input);
30 | }
31 |
32 | public static void v(String tag, String input) {
33 | if (verbose) Log.v(tag, input);
34 | }
35 |
36 | public static void d(String tag, String input) {
37 | if (debug) Log.d(tag, input);
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014 LIFX Labs
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/transport_manager/lan/gateway_discovery/LFXGatewayDiscoveryTableEntry.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXGatewayDiscoveryTableEntry.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.transport_manager.lan.gateway_discovery;
10 |
11 | import lifx.java.android.entities.internal.LFXGatewayDescriptor;
12 |
13 | public class LFXGatewayDiscoveryTableEntry {
14 | private LFXGatewayDescriptor gatewayDescriptor;
15 | private long lastDiscoveryResponseDate;
16 |
17 | public LFXGatewayDescriptor getGatewayDescriptor() {
18 | return gatewayDescriptor;
19 | }
20 |
21 | public void setGatewayDescriptor(LFXGatewayDescriptor gatewayDescriptor) {
22 | this.gatewayDescriptor = gatewayDescriptor;
23 | }
24 |
25 | public long getLastDiscoveryResponseDate() {
26 | return lastDiscoveryResponseDate;
27 | }
28 |
29 | public void setLastDiscoveryResponseDate(long lastDiscoveryResponseDate) {
30 | this.lastDiscoveryResponseDate = lastDiscoveryResponseDate;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/internal/LFXDeviceMapping.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXDeviceMapping.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities.internal;
10 |
11 | import lifx.java.android.entities.internal.LFXBinaryTargetID.TagField;
12 |
13 | public class LFXDeviceMapping {
14 | private String deviceID;
15 |
16 | private LFXSiteID siteID;
17 | private TagField tagField = new TagField();
18 |
19 | public boolean matchesDeviceID(String deviceID) {
20 | return this.deviceID.equals(deviceID);
21 | }
22 |
23 | public void setDeviceID(String deviceID) {
24 | this.deviceID = deviceID;
25 | }
26 |
27 | public void setSiteID(LFXSiteID siteID) {
28 | this.siteID = siteID;
29 | }
30 |
31 | public void setTagField(TagField tagField) {
32 | this.tagField = tagField;
33 | }
34 |
35 | public String getDeviceId() {
36 | return deviceID;
37 | }
38 |
39 | public LFXSiteID getSiteID() {
40 | return siteID;
41 | }
42 |
43 | public TagField getTagField() {
44 | return tagField;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/internal/LFXTagMapping.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXTagMapping.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities.internal;
10 |
11 | import lifx.java.android.entities.internal.LFXBinaryTargetID.TagField;
12 |
13 | public class LFXTagMapping
14 | {
15 | private String tag;
16 |
17 | private LFXSiteID siteID;
18 | private TagField tagField;
19 |
20 | // Use this for uniqueing a TagMapping
21 | public boolean matchesSiteIDAndTagField( LFXSiteID siteID, TagField tagField)
22 | {
23 | return tagField.equals( this.tagField) && siteID.equals( this.siteID);
24 | }
25 |
26 | // Use this for routing outgoing messages
27 | public boolean matchesTag( String tag)
28 | {
29 | return tag.equals( this.tag);
30 | }
31 |
32 | public void setTagField( TagField tagField)
33 | {
34 | this.tagField = tagField;
35 | }
36 |
37 | public void setTag( String tag)
38 | {
39 | this.tag = tag;
40 | }
41 |
42 | public void setSiteID( LFXSiteID siteID)
43 | {
44 | this.siteID = siteID;
45 | }
46 |
47 | public TagField getTagField()
48 | {
49 | return tagField;
50 | }
51 |
52 | public String getTag()
53 | {
54 | return tag;
55 | }
56 |
57 | public LFXSiteID getSiteID()
58 | {
59 | return siteID;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/examples/res/layout/lifx_main_activity_layout.xml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
17 |
18 |
23 |
24 |
31 |
32 |
39 |
40 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/examples/res/layout/lifx_list_sample_layout.xml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
17 |
18 |
27 |
28 |
34 |
35 |
44 |
45 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/client/LFXClient.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXClient.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.client;
10 |
11 | import android.content.Context;
12 |
13 | import lifx.java.android.internal.LFXWiFiObserver;
14 | import lifx.java.android.internal.LFXWiFiObserver.LFXWiFiObserverCallback;
15 | import lifx.java.android.network_context.LFXNetworkContext;
16 | import lifx.java.android.network_context.internal.transport_manager.lan.LFXLANTransportManager;
17 |
18 | public class LFXClient {
19 | private static LFXClient sharedInstance;
20 | private LFXNetworkContext localNetworkContext;
21 |
22 | public static LFXClient getSharedInstance(Context context) {
23 | if (sharedInstance == null) {
24 | sharedInstance = new LFXClient(context);
25 | }
26 |
27 | return sharedInstance;
28 | }
29 |
30 | private LFXClient(Context context) {
31 | super();
32 |
33 | LFXWiFiObserver.getSharedInstance(context).addObserverObjectWithCallback(this, new LFXWiFiObserverCallback() {
34 | @Override
35 | public void run(Object context, LFXWiFiObserver observer) {
36 | LFXClient client = (LFXClient) context;
37 | client.getLocalNetworkContext().resetAllCaches();
38 | }
39 | });
40 | }
41 |
42 | public LFXNetworkContext getLocalNetworkContext() {
43 | if (localNetworkContext == null) {
44 | localNetworkContext = LFXNetworkContext.initWithClientTransportManagerAndName(this, new LFXLANTransportManager(), "LAN");
45 | }
46 |
47 | return localNetworkContext;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/internal/LFXMessageObservationDescriptor.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXMessageObservationDescriptor.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities.internal;
10 |
11 | public class LFXMessageObservationDescriptor {
12 | public interface LFXMessageObserverCallback {
13 | public void run(Object context, LFXMessage message);
14 | }
15 | // typedef void (^LFXMessageObserverCallback)(LFXMessage *message);
16 |
17 | // All Observation Descriptors have a callback
18 | private LFXMessageObserverCallback callback;
19 |
20 | // Observers that were created with an 'observer object' will have this property set
21 | private Object observingObject;
22 |
23 | // An unsafe_unretained reference to .observingObject is stored, and this method can
24 | // be used to compare the two. This is encapsulated to limit the potential scope of
25 | // dead reference bugs.
26 | private Object observingObjectUnsafeReference;
27 |
28 | public void setObservingObject(Object observingObject) {
29 | this.observingObject = observingObject;
30 | this.observingObjectUnsafeReference = observingObject;
31 | }
32 |
33 | public Object getObservingObject() {
34 | return observingObject;
35 | }
36 |
37 | public boolean observingObjectWasEqualTo(Object object) {
38 | return this.observingObjectUnsafeReference == object;
39 | }
40 |
41 | public LFXMessageObserverCallback getCallback() {
42 | return callback;
43 | }
44 |
45 | public void setCallback(LFXMessageObserverCallback callback) {
46 | this.callback = callback;
47 | }
48 | }
49 |
50 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/util/LFXTimerUtils.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXTimerUtils.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.util;
10 |
11 | import java.util.Timer;
12 | import java.util.TimerTask;
13 |
14 | import android.os.Handler;
15 | import android.os.Looper;
16 |
17 | public class LFXTimerUtils {
18 | private final static String TAG = LFXTimerUtils.class.getSimpleName();
19 |
20 | private static class MainThreadRunnableTimerTask extends TimerTask {
21 | private Runnable task;
22 |
23 | public MainThreadRunnableTimerTask(Runnable task) {
24 | this.task = task;
25 | }
26 |
27 | @Override
28 | public void run() {
29 | Handler handler = new Handler(Looper.getMainLooper());
30 | handler.post(task);
31 | }
32 | }
33 |
34 | // public static Timer getTimerTaskWithPeriod( Runnable task, long period, boolean immediate)
35 | // {
36 | // return getTimerTaskWithPeriod(task,period,immediate,"UnnamedTimerTask");
37 | // }
38 |
39 | public static Timer getTimerTaskWithPeriod(Runnable task, long period, boolean immediate, String name) {
40 | //LFXLog.d(TAG, "getTimerTaskWithPeriod() - " + name + ", " + period);
41 | Timer timer = new Timer();
42 | long delay = 0L;
43 |
44 | if (!immediate) {
45 | delay = period;
46 | }
47 |
48 | timer.scheduleAtFixedRate(new MainThreadRunnableTimerTask(task), delay, period);
49 | return timer;
50 | }
51 |
52 | public static void scheduleDelayedTask(Runnable task, long delay) {
53 | Handler handler = new Handler(Looper.getMainLooper());
54 | handler.postDelayed(task, delay);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/examples/src/com/example/lifx_sdk_samples/LFXSDKLightListAdapter.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSDKLightListAdapter.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package com.example.lifx_sdk_samples;
10 |
11 | import java.lang.ref.SoftReference;
12 | import java.util.ArrayList;
13 |
14 | import android.app.Activity;
15 | import android.view.View;
16 | import android.view.ViewGroup;
17 | import android.widget.BaseAdapter;
18 | import android.widget.TextView;
19 |
20 | import lifx.java.android.light.LFXLight;
21 |
22 | public class LFXSDKLightListAdapter extends BaseAdapter
23 | {
24 | private ArrayList lights = new ArrayList();
25 | private SoftReference activity;
26 |
27 | public LFXSDKLightListAdapter( Activity activity)
28 | {
29 | this.activity = new SoftReference( activity);
30 | }
31 |
32 | public void updateWithLights( ArrayList newLights)
33 | {
34 | lights.clear();
35 |
36 | lights.addAll( newLights);
37 |
38 | notifyDataSetChanged();
39 | }
40 |
41 | @Override
42 | public int getCount()
43 | {
44 | return lights.size();
45 | }
46 |
47 | @Override
48 | public Object getItem( int position)
49 | {
50 | return lights.get( position);
51 | }
52 |
53 | @Override
54 | public long getItemId( int position)
55 | {
56 | return position;
57 | }
58 |
59 | @Override
60 | public View getView( int position, View convertView, ViewGroup listView)
61 | {
62 | if( convertView == null)
63 | {
64 | convertView = activity.get().getLayoutInflater().inflate( R.layout.lifx_list_item_layout, null);
65 | }
66 |
67 | LFXLight light = (LFXLight) getItem( position);
68 |
69 | TextView labelView = (TextView) convertView.findViewById( R.id.light_label);
70 | labelView.setText( light.getLabel());
71 |
72 | return convertView;
73 | }
74 | }
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/LFXLightTarget.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXLightTarget.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.entities.LFXTypes.LFXFuzzyPowerState;
14 | import lifx.java.android.entities.LFXTypes.LFXPowerState;
15 | import lifx.java.android.entities.internal.LFXTarget;
16 | import lifx.java.android.entities.internal.LFXTarget.LFXTargetType;
17 | import lifx.java.android.light.LFXLight;
18 |
19 | public abstract class LFXLightTarget {
20 | private LFXTarget target;
21 | private LFXTargetType targetType;
22 | private ArrayList lights;
23 | protected String label;
24 | protected LFXHSBKColor color;
25 | protected LFXFuzzyPowerState fuzzyPowerState;
26 |
27 | public LFXTarget getTarget() {
28 | return target;
29 | }
30 |
31 | public void setTarget(LFXTarget target) {
32 | this.target = target;
33 | }
34 |
35 | public LFXTargetType getTargetType() {
36 | return targetType;
37 | }
38 |
39 | public ArrayList getLights() {
40 | return lights;
41 | }
42 |
43 | // Light State
44 | public String getLabel() {
45 | if (label == null) {
46 | return "Unknown";
47 | }
48 |
49 | return label;
50 | }
51 |
52 | public LFXHSBKColor getColor() {
53 | return color;
54 | }
55 |
56 | public LFXFuzzyPowerState getFuzzyPowerState() {
57 | return fuzzyPowerState;
58 | }
59 |
60 | // Light Control
61 | public abstract void setLabel(String label);
62 |
63 | public abstract void setColor(LFXHSBKColor color);
64 |
65 | public abstract void setColorOverDuration(LFXHSBKColor color, long duration);
66 |
67 | public abstract void setPowerState(LFXPowerState powerState);
68 | }
69 |
--------------------------------------------------------------------------------
/examples/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
9 |
10 |
12 |
13 |
15 |
16 |
18 |
19 |
21 |
22 |
25 |
26 |
31 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
44 |
45 |
46 |
49 |
50 |
51 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/examples/src/com/example/lifx_sdk_samples/LFXSDKTaggedLightCollectionListAdapter.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSDKTaggedLightCollectionListAdapter.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package com.example.lifx_sdk_samples;
10 |
11 | import java.lang.ref.SoftReference;
12 | import java.util.ArrayList;
13 |
14 | import lifx.java.android.light.LFXLightCollection;
15 | import lifx.java.android.light.LFXTaggedLightCollection;
16 | import android.app.Activity;
17 | import android.view.View;
18 | import android.view.ViewGroup;
19 | import android.widget.BaseAdapter;
20 | import android.widget.TextView;
21 |
22 | public class LFXSDKTaggedLightCollectionListAdapter extends BaseAdapter
23 | {
24 | private ArrayList lightCollections = new ArrayList();
25 | private SoftReference activity;
26 |
27 | public LFXSDKTaggedLightCollectionListAdapter( Activity activity)
28 | {
29 | this.activity = new SoftReference( activity);
30 | }
31 |
32 | public void updateWithLightCollections( ArrayList newLights)
33 | {
34 | lightCollections.clear();
35 |
36 | lightCollections.addAll( newLights);
37 |
38 | notifyDataSetChanged();
39 | }
40 |
41 | @Override
42 | public int getCount()
43 | {
44 | return lightCollections.size();
45 | }
46 |
47 | @Override
48 | public Object getItem( int position)
49 | {
50 | return lightCollections.get( position);
51 | }
52 |
53 | @Override
54 | public long getItemId( int position)
55 | {
56 | return position;
57 | }
58 |
59 | @Override
60 | public View getView( int position, View convertView, ViewGroup listView)
61 | {
62 | if( convertView == null)
63 | {
64 | convertView = activity.get().getLayoutInflater().inflate( R.layout.lifx_list_item_layout, null);
65 | }
66 |
67 | LFXLightCollection light = (LFXLightCollection) getItem( position);
68 |
69 | TextView labelView = (TextView) convertView.findViewById( R.id.light_label);
70 | labelView.setText( light.getLabel());
71 |
72 | return convertView;
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/internal/LFXSiteID.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSiteID.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities.internal;
10 |
11 | import lifx.java.android.util.LFXByteUtils;
12 |
13 | public class LFXSiteID {
14 | private static final int LFX_SITE_ID_NUMBER_OF_BYTES = 6;
15 |
16 | private byte[] data;
17 |
18 | private LFXSiteID() {
19 | data = new byte[LFX_SITE_ID_NUMBER_OF_BYTES];
20 | }
21 |
22 | // The canonical representation of a Site ID is a hex string. This is the form
23 | // used in the LIFX Cloud API.
24 | public static LFXSiteID getSiteIDWithString(String siteIDString) {
25 | byte[] data = LFXByteUtils.hexStringToByteArray(siteIDString);
26 | return getSiteIDWithData(data);
27 | }
28 |
29 | public String getStringValue() {
30 | if (this.isZeroSite()) {
31 | return "*";
32 | }
33 |
34 | return LFXByteUtils.byteArrayToHexString(data);
35 | }
36 |
37 | // The LIFX Protocol uses 6-bytes to represent a Site ID
38 | public static LFXSiteID getSiteIDWithData(byte[] data) {
39 | LFXSiteID siteID = new LFXSiteID();
40 | LFXByteUtils.copyBytesIntoByteArray(siteID.data, data);
41 | return siteID;
42 | }
43 |
44 | public byte[] getDataValue() {
45 | return data;
46 | }
47 |
48 | // When a device hasn't been added to a site yet, it will have a 'zero' Site ID.
49 | public static LFXSiteID getZeroSiteID() {
50 | byte[] bytes = new byte[]{0, 0, 0, 0, 0, 0};
51 | return getSiteIDWithData(bytes);
52 | }
53 |
54 | public boolean isZeroSite() {
55 | return LFXByteUtils.isByteArrayEmpty(data);
56 | }
57 |
58 | // A shorter string representation - useful for logging and diagnostics
59 | public String getDebugStringValue() {
60 | return "LFXSiteID: " + LFXByteUtils.byteArrayToHexString(data);
61 | }
62 |
63 | public String toString() {
64 | return getDebugStringValue();
65 | }
66 |
67 | @Override
68 | public boolean equals(Object aSiteID) {
69 | if (aSiteID == null) {
70 | return false;
71 | }
72 |
73 | if (!LFXByteUtils.areByteArraysEqual(data, ((LFXSiteID)aSiteID).data)) {
74 | return false;
75 | }
76 |
77 | return true;
78 | }
79 |
80 | @Override
81 | public Object clone() {
82 | return getSiteIDWithData(data);
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/internal/LFXBinaryPath.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXBinaryPath.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities.internal;
10 |
11 | import java.util.StringTokenizer;
12 |
13 | public class LFXBinaryPath {
14 | public static LFXBinaryPath getPathWithString(String stringPath) {
15 | StringTokenizer tokenizer = new StringTokenizer(stringPath, "/");
16 |
17 | int tokens = tokenizer.countTokens();
18 |
19 | if (tokens != 2) {
20 | return null;
21 | }
22 |
23 | String siteString = tokenizer.nextToken();
24 | String targetString = tokenizer.nextToken();
25 | return getPathWithSiteIDAndTargetID(LFXSiteID.getSiteIDWithString(siteString), LFXBinaryTargetID.getTargetIDWithString(targetString));
26 | }
27 |
28 | public String getStringValue() {
29 | return toString();
30 | }
31 |
32 | public String toString() {
33 | return siteID.toString() + "/" + targetID.toString();
34 | }
35 |
36 | public static LFXBinaryPath getPathWithSiteIDAndTargetID(LFXSiteID siteID, LFXBinaryTargetID targetID) {
37 | LFXBinaryPath path = new LFXBinaryPath();
38 | path.siteID = siteID;
39 | path.targetID = targetID;
40 | return path;
41 | }
42 |
43 | private LFXSiteID siteID;
44 | private LFXBinaryTargetID targetID;
45 |
46 | public LFXSiteID getSiteID() {
47 | return siteID;
48 | }
49 |
50 | public LFXBinaryTargetID getBinaryTargetID() {
51 | return targetID;
52 | }
53 |
54 | public String getDebugStringValue() {
55 | return toString();
56 | }
57 |
58 | public boolean equals(LFXBinaryPath aBinaryPath) {
59 | if (aBinaryPath == null) {
60 | return false;
61 | }
62 |
63 | if (!this.targetID.equals(aBinaryPath.targetID)) {
64 | return false;
65 | }
66 |
67 | if (!this.siteID.equals(aBinaryPath.siteID)) {
68 | return false;
69 | }
70 |
71 | return true;
72 | }
73 |
74 | public static LFXBinaryPath getBroadcastBinaryPathWithSiteID(LFXSiteID siteID) {
75 | return getPathWithSiteIDAndTargetID(siteID, LFXBinaryTargetID.getBroadcastTargetID());
76 | }
77 |
78 | public Object clone() {
79 | LFXBinaryPath newPath = new LFXBinaryPath();
80 | newPath.siteID = this.siteID;
81 | newPath.targetID = this.targetID;
82 | return newPath;
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/examples/src/com/example/lifx_sdk_samples/LFXSDKSamplesActivity.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSDKSamplesActivity.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package com.example.lifx_sdk_samples;
10 |
11 | import lifx.java.android.client.LFXClient;
12 | import lifx.java.android.network_context.LFXNetworkContext;
13 | import android.app.Activity;
14 | import android.content.Context;
15 | import android.content.Intent;
16 | import android.net.wifi.WifiManager;
17 | import android.net.wifi.WifiManager.MulticastLock;
18 | import android.os.Bundle;
19 | import android.view.View;
20 |
21 | public class LFXSDKSamplesActivity extends Activity
22 | {
23 | private boolean shouldStopLifxOnPause;
24 | private LFXNetworkContext networkContext;
25 | private MulticastLock ml = null;
26 |
27 | @Override
28 | protected void onCreate( Bundle savedInstanceState)
29 | {
30 | super.onCreate( savedInstanceState);
31 |
32 | setContentView( R.layout.lifx_main_activity_layout);
33 |
34 | // A Multicast lock should be acquired, as some phones disable UDP broadcast / recieve
35 | WifiManager wifi;
36 | wifi = (WifiManager) getSystemService( Context.WIFI_SERVICE);
37 | ml = wifi.createMulticastLock( "lifx_samples_tag");
38 | ml.acquire();
39 |
40 | networkContext = LFXClient.getSharedInstance( getApplicationContext()).getLocalNetworkContext();
41 | networkContext.connect();
42 | }
43 |
44 | @Override
45 | protected void onResume()
46 | {
47 | super.onResume();
48 |
49 | shouldStopLifxOnPause = true;
50 | }
51 |
52 | public void pressedLabelChange( View v)
53 | {
54 | Intent intent = new Intent( getApplicationContext(), LFXSDKLightEditLabelActivity.class);
55 | shouldStopLifxOnPause = false;
56 | startActivity( intent);
57 | }
58 |
59 | public void pressedRandomColor( View v)
60 | {
61 | Intent intent = new Intent( getApplicationContext(), LFXSDKLightRandomColorActivity.class);
62 | shouldStopLifxOnPause = false;
63 | startActivity( intent);
64 | }
65 |
66 | public void pressedPowerChange( View v)
67 | {
68 | Intent intent = new Intent( getApplicationContext(), LFXSDKLightPowerActivity.class);
69 | shouldStopLifxOnPause = false;
70 | startActivity( intent);
71 | }
72 |
73 | @Override
74 | protected void onPause()
75 | {
76 | super.onPause();
77 |
78 | if( shouldStopLifxOnPause)
79 | {
80 | System.out.println( "Stop LIFX");
81 | networkContext.disconnect();
82 |
83 | if( ml != null)
84 | {
85 | ml.release();
86 | }
87 | }
88 | else
89 | {
90 | System.out.println( "Don't Stop LIFX");
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/internal/LFXBinaryTypes.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXBinaryTypes.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities.internal;
10 |
11 | import lifx.java.android.entities.LFXHSBKColor;
12 | import lifx.java.android.entities.LFXTypes.LFXPowerState;
13 | import lifx.java.android.entities.internal.structle.LxProtocolLight;
14 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt16;
15 |
16 | public class LFXBinaryTypes {
17 | public static UInt16 getLFXProtocolPowerLevelFromLFXPowerState(LFXPowerState powerState) {
18 | switch (powerState) {
19 | case OFF:
20 | return new UInt16(0);
21 | case ON:
22 | return new UInt16(1);
23 | }
24 |
25 | return new UInt16(1);
26 | }
27 |
28 | public static LFXPowerState getLFXPowerStateFromLFXProtocolPowerLevel(UInt16 powerLevel) {
29 | if (powerLevel.getValue() == 0) {
30 | return LFXPowerState.OFF;
31 | } else {
32 | return LFXPowerState.ON;
33 | }
34 | }
35 |
36 | public static LFXHSBKColor getLFXHSBKColorFromLXProtocolLightHsbk(LxProtocolLight.Hsbk protocolHsbk) {
37 | float hue = (float) protocolHsbk.getHue().getValue() * 360.0f / (float) UInt16.MAX_U16_VALUE;
38 | float saturation = (float) protocolHsbk.getSaturation().getValue() / (float) UInt16.MAX_U16_VALUE;
39 | float brightness = (float) protocolHsbk.getBrightness().getValue() / (float) UInt16.MAX_U16_VALUE;
40 | int kelvin = protocolHsbk.getKelvin().getValue();
41 |
42 | LFXHSBKColor color = LFXHSBKColor.getColor(hue, saturation, brightness, kelvin);
43 |
44 | return color;
45 | }
46 |
47 | public static LxProtocolLight.Hsbk getLXProtocolLightHsbkFromLFXHSBKColor(LFXHSBKColor color) {
48 | int hue = (int) (color.getHue() / 360.0 * (float) UInt16.MAX_U16_VALUE);
49 | int saturation = (int) (color.getSaturation() * (float) UInt16.MAX_U16_VALUE);
50 | int brightness = (int) (color.getBrightness() * (float) UInt16.MAX_U16_VALUE);
51 | int kelvin = color.getKelvin();
52 |
53 | UInt16 wrappedHue = new UInt16(hue);
54 | UInt16 wrappedSaturation = new UInt16(saturation);
55 | UInt16 wrappedBrightness = new UInt16(brightness);
56 | UInt16 wrappedKelvin = new UInt16(kelvin);
57 |
58 | Object padding = new Object();
59 |
60 | LxProtocolLight.Hsbk lightHSBK = new LxProtocolLight.Hsbk(padding, wrappedHue, wrappedSaturation, wrappedBrightness, wrappedKelvin);
61 |
62 | return lightHSBK;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/internal/LFXTarget.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXTarget.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities.internal;
10 |
11 | public class LFXTarget {
12 |
13 | public enum LFXTargetType {
14 | BROADCAST,
15 | DEVICE,
16 | TAG,
17 | }
18 |
19 | private LFXTargetType targetType;
20 | private String deviceID;
21 | private String tag;
22 |
23 | public LFXTargetType getTargetType() {
24 | return targetType;
25 | }
26 |
27 | public String getTag() {
28 | return tag;
29 | }
30 |
31 | public String getDeviceID() {
32 | return deviceID;
33 | }
34 |
35 | public static LFXTarget getBroadcastTarget() {
36 | LFXTarget target = new LFXTarget();
37 | target.targetType = LFXTargetType.BROADCAST;
38 | return target;
39 | }
40 |
41 | public static LFXTarget getDeviceTargetWithDeviceID(String deviceID) {
42 | LFXTarget target = new LFXTarget();
43 | target.targetType = LFXTargetType.DEVICE;
44 | target.deviceID = deviceID;
45 | return target;
46 | }
47 |
48 | public static LFXTarget getTagTargetWithTag(String tag) {
49 | LFXTarget target = new LFXTarget();
50 | target.targetType = LFXTargetType.TAG;
51 | target.tag = tag;
52 | return target;
53 | }
54 |
55 | public String toString() {
56 | return "" + getStringValue();
57 | }
58 |
59 | public String getStringValue() {
60 | switch (targetType) {
61 | case BROADCAST:
62 | return "*";
63 | case TAG:
64 | return "#" + tag;
65 | case DEVICE:
66 | return deviceID;
67 | }
68 |
69 | return "Unknown Target Type";
70 | }
71 |
72 | public static LFXTarget getTargetWithString(String stringValue) {
73 | if (stringValue.contains("*")) {
74 | return getBroadcastTarget();
75 | }
76 |
77 | if (stringValue.contains("#")) {
78 | String tagString = stringValue.substring(stringValue.indexOf('#') + 1);
79 | return getTagTargetWithTag(tagString);
80 | } else {
81 | return getDeviceTargetWithDeviceID(stringValue);
82 | }
83 | }
84 |
85 | public boolean equals(LFXTarget aTarget) {
86 | if (aTarget == null) {
87 | return false;
88 | }
89 |
90 | if (this.targetType != aTarget.targetType) {
91 | return false;
92 | }
93 |
94 | switch (targetType) {
95 | case BROADCAST:
96 | return true;
97 | case DEVICE:
98 | return deviceID.equals(aTarget.deviceID);
99 | case TAG:
100 | return tag.equals(aTarget.tag);
101 | }
102 |
103 | return false;
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/light/internal/LFXAllLightsCollection.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXAllLightsCollection.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.light.internal;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.entities.LFXHSBKColor;
14 | import lifx.java.android.entities.LFXTypes.LFXPowerState;
15 | import lifx.java.android.entities.internal.LFXBinaryTypes;
16 | import lifx.java.android.entities.internal.LFXMessage;
17 | import lifx.java.android.entities.internal.LFXTarget;
18 | import lifx.java.android.entities.internal.LFXTarget.LFXTargetType;
19 | import lifx.java.android.entities.internal.structle.LxProtocolDevice;
20 | import lifx.java.android.entities.internal.structle.LxProtocolLight;
21 | import lifx.java.android.entities.internal.structle.LxProtocol.Type;
22 | import lifx.java.android.entities.internal.structle.LxProtocolLight.Hsbk;
23 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt16;
24 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt32;
25 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt8;
26 | import lifx.java.android.light.LFXLight;
27 | import lifx.java.android.light.LFXLightCollection;
28 | import lifx.java.android.network_context.LFXNetworkContext;
29 |
30 | public class LFXAllLightsCollection extends LFXLightCollection {
31 | private final static String TAG = LFXAllLightsCollection.class.getSimpleName();
32 |
33 | public static LFXAllLightsCollection getLightCollectionWithNetworkContext(LFXNetworkContext networkContext) {
34 | LFXAllLightsCollection collection = new LFXAllLightsCollection();
35 | collection.networkContext = networkContext;
36 | collection.lights = new ArrayList();
37 | return collection;
38 | }
39 |
40 | //private LFXTarget target;
41 |
42 | public LFXTargetType getTargetType() {
43 | return LFXTargetType.BROADCAST;
44 | }
45 |
46 | public String getLabel() {
47 | return "All Lights";
48 | }
49 |
50 | public LFXTarget getTarget() {
51 | return LFXTarget.getBroadcastTarget();
52 | }
53 |
54 | // Setters
55 | public void setColor(LFXHSBKColor color) {
56 | setColorOverDuration(color, 250);
57 | }
58 |
59 | public void setColorOverDuration(LFXHSBKColor color, long duration) {
60 | LFXMessage lightSet = LFXMessage.messageWithTypeAndTarget(Type.LX_PROTOCOL_LIGHT_SET, getTarget());
61 | Object padding = new Object();
62 | UInt8 stream = new UInt8(0);
63 | Hsbk protocolColor = LFXBinaryTypes.getLXProtocolLightHsbkFromLFXHSBKColor(color);
64 | UInt32 protocolDuration = new UInt32(duration);
65 | LxProtocolLight.Set payload = new LxProtocolLight.Set(padding, stream, protocolColor, protocolDuration);
66 | lightSet.setPayload(payload);
67 | networkContext.sendMessage(lightSet);
68 | }
69 |
70 | public void setPowerState(LFXPowerState powerState) {
71 | LFXMessage setPower = LFXMessage.messageWithTypeAndTarget(Type.LX_PROTOCOL_DEVICE_SET_POWER, getTarget());
72 | Object padding = new Object();
73 | UInt16 protocolPowerLevel = LFXBinaryTypes.getLFXProtocolPowerLevelFromLFXPowerState(powerState);
74 | LxProtocolDevice.SetPower payload = new LxProtocolDevice.SetPower(padding, protocolPowerLevel);
75 | setPower.setPayload(payload);
76 | networkContext.sendMessage(setPower);
77 | }
78 |
79 | @Override
80 | public void setLabel(String label) {
81 | // DO NOTHING
82 | }
83 |
84 | @Override
85 | public void handleMessage(LFXMessage message) {
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/LFXHSBKColor.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXHSBKColor.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities;
10 |
11 | public class LFXHSBKColor implements Cloneable {
12 | private static final float MINIMUM_SATURATION = 0.0001f;
13 |
14 | private float hue; // 0.0 - 360.0
15 | private float saturation; // 0.0 - 1.0
16 | private float brightness; // 0.0 - 1.0
17 | private int kelvin; // 0 - 10,000
18 |
19 | private LFXHSBKColor() {
20 | this.hue = 0.0f;
21 | this.saturation = 0.0f;
22 | this.brightness = 1.0f;
23 | this.kelvin = 3500;
24 | }
25 |
26 | public float getHue() {
27 | return hue;
28 | }
29 |
30 | public float getSaturation() {
31 | return saturation;
32 | }
33 |
34 | public float getBrightness() {
35 | return brightness;
36 | }
37 |
38 | public int getKelvin() {
39 | return kelvin;
40 | }
41 |
42 | public static LFXHSBKColor getColor(float hue, float saturation, float brightness, int kelvin) {
43 | LFXHSBKColor color = new LFXHSBKColor();
44 | color.hue = hue;
45 | color.saturation = saturation;
46 | color.brightness = brightness;
47 | color.kelvin = kelvin;
48 | return color;
49 | }
50 |
51 | public boolean isWhite() // Returns YES if saturation = 0.0;
52 | {
53 | if (saturation <= MINIMUM_SATURATION) {
54 | return true;
55 | }
56 |
57 | return false;
58 | }
59 |
60 | public String toString() // "HSBK: (0.1, 0.4, 0.2, 5000)"
61 | {
62 | return "HSBK: (" + hue + ", " + saturation + ", " + brightness + ", " + kelvin + ")";
63 | }
64 |
65 | public static LFXHSBKColor averageOfColors(LFXHSBKColor[] colors) {
66 | if (colors.length == 0) {
67 | return null;
68 | }
69 |
70 | float hueXTotal = 0;
71 | float hueYTotal = 0;
72 | float saturationTotal = 0;
73 | float brightnessTotal = 0;
74 | long kelvinTotal = 0;
75 |
76 | for (LFXHSBKColor aColor : colors) {
77 | hueXTotal += Math.sin(aColor.hue * Math.PI / 180.0);
78 | hueYTotal += Math.cos(aColor.hue * Math.PI / 180.0);
79 | saturationTotal += aColor.saturation;
80 | brightnessTotal += aColor.brightness;
81 |
82 | if (aColor.kelvin == 0) {
83 | kelvinTotal += 3500;
84 | } else {
85 | kelvinTotal += aColor.kelvin;
86 | }
87 | }
88 |
89 | float M_1_PI = (float) (1.0f / Math.PI);
90 |
91 | float hue = (float) (Math.atan2(hueXTotal, hueYTotal) * 0.5 * M_1_PI);
92 | if (hue < 0.0) hue += 1.0;
93 | float saturation = saturationTotal / (float) colors.length;
94 | float brightness = brightnessTotal / (float) colors.length;
95 | int kelvin = (int) (kelvinTotal / colors.length);
96 |
97 | return LFXHSBKColor.getColor(hue, saturation, brightness, kelvin);
98 | }
99 |
100 | @Override
101 | protected Object clone() throws CloneNotSupportedException {
102 | LFXHSBKColor newColor = new LFXHSBKColor();
103 | newColor.hue = this.hue;
104 | newColor.saturation = this.saturation;
105 | newColor.brightness = this.brightness;
106 | newColor.kelvin = this.kelvin;
107 | return newColor;
108 | }
109 |
110 | @Override
111 | public boolean equals(Object aColor) {
112 | if (aColor == null) {
113 | return false;
114 | }
115 |
116 |
117 | if (((LFXHSBKColor)aColor).hue != this.hue ||
118 | ((LFXHSBKColor)aColor).saturation != this.saturation ||
119 | ((LFXHSBKColor)aColor).brightness != this.brightness ||
120 | ((LFXHSBKColor)aColor).kelvin != this.kelvin) {
121 | return false;
122 | }
123 |
124 | return true;
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/internal/LFXGatewayDescriptor.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXGatewayDescriptor.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities.internal;
10 |
11 | import lifx.java.android.entities.internal.structle.LxProtocolDevice;
12 | import lifx.java.android.entities.internal.structle.LxProtocolDevice.Service;
13 | import lifx.java.android.internal.LFXWiFiObserver;
14 |
15 | public class LFXGatewayDescriptor {
16 | private String host;
17 | private int port;
18 | private LFXBinaryPath path;
19 | private LxProtocolDevice.Service service;
20 |
21 | public LFXGatewayDescriptor() {
22 |
23 | }
24 |
25 | public static LFXGatewayDescriptor getGatewayDescriptorWithHostPortPathService(String host, int port, LFXBinaryPath path, LxProtocolDevice.Service service) {
26 | LFXGatewayDescriptor gatewayDescriptor = new LFXGatewayDescriptor();
27 | gatewayDescriptor.host = host;
28 | gatewayDescriptor.port = port;
29 | gatewayDescriptor.path = path;
30 | gatewayDescriptor.service = service;
31 | return gatewayDescriptor;
32 | }
33 |
34 | public static LFXGatewayDescriptor getBroadcastGatewayDescriptor() {
35 | return getGatewayDescriptorWithHostPortPathService(LFXWiFiObserver.getWiFiBroadcastAddress(), 56700, null, Service.LX_PROTOCOL_DEVICE_SERVICE_UDP);
36 | }
37 |
38 | public static LFXGatewayDescriptor getClientPeerToPeerGatewayDescriptor() {
39 | return getGatewayDescriptorWithHostPortPathService(LFXWiFiObserver.getWiFiBroadcastAddress(), 56750, null, Service.LX_PROTOCOL_DEVICE_SERVICE_UDP);
40 | }
41 |
42 | public static LFXGatewayDescriptor getSoftAPGatewayDescriptor() {
43 | return getGatewayDescriptorWithHostPortPathService("172.16.0.1", 56700, null, Service.LX_PROTOCOL_DEVICE_SERVICE_TCP);
44 | }
45 |
46 | public boolean isBroadcastGateway() {
47 | return this.equals(getBroadcastGatewayDescriptor());
48 | }
49 |
50 | public boolean isClientPeerToPeerGateway() {
51 | return this.equals(getClientPeerToPeerGatewayDescriptor());
52 | }
53 |
54 | public boolean isSoftAPGateway() {
55 | return this.equals(getSoftAPGatewayDescriptor());
56 | }
57 |
58 | public String getHost() {
59 | return host;
60 | }
61 |
62 | public int getPort() {
63 | return port;
64 | }
65 |
66 | public LFXBinaryPath getPath() {
67 | return path;
68 | }
69 |
70 | public LxProtocolDevice.Service getService() {
71 | return service;
72 | }
73 |
74 | public String getProtocolString() {
75 | return (service != null) ? service.toString() : "(Service was null!)";
76 | }
77 |
78 | public String toString() {
79 | if (path != null) {
80 | return "LFXGatewayDescriptor - Host: " + host + ", Port: " + port + ", Path: " + path.toString() + ", Protocol: " + getProtocolString();
81 | } else {
82 | return "LFXGatewayDescriptor - Host: " + host + ", Port: " + port + ", Path: " + path + ", Protocol: " + getProtocolString();
83 | }
84 | }
85 |
86 | public boolean equals(LFXGatewayDescriptor aGatewayDescriptor) {
87 | if (aGatewayDescriptor == null) {
88 | return false;
89 | }
90 |
91 | if (!aGatewayDescriptor.getHost().equals(this.host)) {
92 | return false;
93 | }
94 |
95 | if (aGatewayDescriptor.getPort() != this.port) {
96 | return false;
97 | }
98 |
99 | if (aGatewayDescriptor.getService() != this.service) {
100 | return false;
101 | }
102 |
103 | return true;
104 | }
105 |
106 | public Object clone() {
107 | LFXGatewayDescriptor newGatewayDescriptor = new LFXGatewayDescriptor();
108 | newGatewayDescriptor.host = this.host;
109 | newGatewayDescriptor.port = this.port;
110 | newGatewayDescriptor.path = this.path;
111 | newGatewayDescriptor.service = this.service;
112 | return newGatewayDescriptor;
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/internal/LFXWiFiObserver.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXWiFiObserver.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.internal;
10 |
11 | import java.util.ArrayList;
12 | import java.util.HashMap;
13 | import java.util.Timer;
14 | import java.util.TimerTask;
15 |
16 | import android.content.Context;
17 |
18 | import lifx.java.android.util.LFXNetworkUtils;
19 |
20 | public class LFXWiFiObserver {
21 | private final static String TAG = LFXWiFiObserver.class.getSimpleName();
22 |
23 | public interface LFXWiFiObserverCallback {
24 | public void run(Object context, LFXWiFiObserver message);
25 | }
26 |
27 | public class LFXWiFiObservationDescriptor {
28 | private Object observingObject;
29 | private LFXWiFiObserverCallback callback;
30 |
31 | public void setObservingObject(Object observingObject) {
32 | this.observingObject = observingObject;
33 | }
34 |
35 | public Object getObservingObject() {
36 | return observingObject;
37 | }
38 |
39 | public void setCallback(LFXWiFiObserverCallback callback) {
40 | this.callback = callback;
41 | }
42 |
43 | public LFXWiFiObserverCallback getCallback() {
44 | return callback;
45 | }
46 | }
47 |
48 | private static LFXWiFiObserver sharedInstance;
49 | private String currentSSID;
50 | private Context context;
51 |
52 | public static LFXWiFiObserver getSharedInstance(Context context) {
53 | if (sharedInstance == null) {
54 | sharedInstance = new LFXWiFiObserver();
55 | sharedInstance.context = context;
56 | }
57 |
58 | return sharedInstance;
59 | }
60 |
61 | public static String getWiFiBroadcastAddress() {
62 | if (sharedInstance != null && sharedInstance.context != null) {
63 | return LFXNetworkUtils.getBroadcastAddress(sharedInstance.context);
64 | } else {
65 | return "255.255.255.255";
66 | }
67 | }
68 |
69 | @SuppressWarnings("unused")
70 | private Runnable getWifiPollTimerTask() {
71 | Runnable wifiPollTimerTask = new TimerTask() {
72 | public void run() {
73 | wifiPollingTimerDidFire();
74 | }
75 | };
76 |
77 | return wifiPollTimerTask;
78 | }
79 |
80 | private LFXWiFiObserver() {
81 | observationDescriptors = new ArrayList();
82 | //wifiStatePollingTimer = LFXTimerUtils.getTimerTaskWithPeriod( getWifiPollTimerTask(), 1000, false);
83 | }
84 |
85 | @SuppressWarnings("unused")
86 | private Timer wifiStatePollingTimer;
87 | private ArrayList observationDescriptors;
88 |
89 | @SuppressWarnings({"unused", "rawtypes"})
90 | private HashMap cachedNetworkInfo;
91 |
92 | private void wifiPollingTimerDidFire() {
93 | }
94 |
95 | @SuppressWarnings({"rawtypes", "unused"})
96 | private HashMap getFreshNetworkInfo() {
97 | return null;
98 | }
99 |
100 | @SuppressWarnings("unused")
101 | private String getCurrentSSID() {
102 | return null;
103 | }
104 |
105 | public boolean isConnectedToLIFXSoftAP() {
106 | return currentSSID.equals("LIFX Bulb");
107 | }
108 |
109 | public void addObserverObjectWithCallback(Object object, LFXWiFiObserverCallback callback) {
110 | LFXWiFiObservationDescriptor observationDescriptor = new LFXWiFiObservationDescriptor();
111 | observationDescriptor.setObservingObject(object);
112 | observationDescriptor.setCallback(callback);
113 | observationDescriptors.add(observationDescriptor);
114 | }
115 |
116 | @SuppressWarnings("unchecked")
117 | public void removeObserverObject(Object object) {
118 | for (LFXWiFiObservationDescriptor anObservationDescriptor : (ArrayList) observationDescriptors.clone()) {
119 | if (anObservationDescriptor.getObservingObject() == object) {
120 | observationDescriptors.remove(anObservationDescriptor);
121 | }
122 | }
123 | }
124 |
125 | @SuppressWarnings("unused")
126 | private void sendObservationCallbacks() {
127 | for (LFXWiFiObservationDescriptor anObservationDescriptor : observationDescriptors) {
128 | anObservationDescriptor.getCallback().run(anObservationDescriptor.getObservingObject(), this);
129 | }
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/util/LFXByteUtils.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXByteUtils.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.util;
10 |
11 | public class LFXByteUtils {
12 | private final static String TAG = LFXByteUtils.class.getSimpleName();
13 |
14 | public static boolean areByteArraysEqual(byte[] byteArray0, byte[] byteArray1) {
15 | if (byteArray0 == null && byteArray1 != null) {
16 | return false;
17 | } else if (byteArray0 != null && byteArray1 == null) {
18 | return false;
19 | } else if (byteArray0 == null && byteArray1 == null) {
20 | return true;
21 | }
22 |
23 | if (byteArray0.length != byteArray1.length) {
24 | return false;
25 | }
26 |
27 | for (int i = 0; i < byteArray0.length; i++) {
28 | if (byteArray0[i] != byteArray1[i]) {
29 | return false;
30 | }
31 | }
32 |
33 | return true;
34 | }
35 |
36 | public static byte[] hexStringToByteArray(String s) {
37 | int len = s.length();
38 |
39 | byte[] data = new byte[len / 2];
40 |
41 | for (int i = 0; i < len; i += 2) {
42 | data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
43 | }
44 |
45 | return data;
46 | }
47 |
48 | final protected static char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
49 |
50 | public static String byteArrayToHexString(byte[] bytes) {
51 | char[] hexChars = new char[bytes.length * 2];
52 | int v;
53 |
54 | for (int j = 0; j < bytes.length; j++) {
55 | v = bytes[j] & 0xFF;
56 | hexChars[j * 2] = hexArray[v >>> 4];
57 | hexChars[j * 2 + 1] = hexArray[v & 0x0F];
58 | }
59 |
60 | return new String(hexChars);
61 | }
62 |
63 | public static void copyBytesIntoByteArrayAtOffset(byte[] dest, byte[] src, int offset) {
64 | for (int i = 0; i < src.length; i++) {
65 | dest[offset + i] = src[i];
66 | }
67 | }
68 |
69 | public static void copyBytesIntoByteArray(byte[] dest, byte[] src) {
70 | copyBytesIntoByteArrayAtOffset(dest, src, 0);
71 | }
72 |
73 | public static void copyBytesIntoByteArrayUpToLength(byte[] dest, byte[] src, int offset) {
74 | for (int i = 0; i < offset; i++) {
75 | dest[i] = src[i];
76 | }
77 | }
78 |
79 | public static void clearByteArray(byte[] bytes) {
80 | for (int i = 0; i < bytes.length; i++) {
81 | bytes[i] = 0;
82 | }
83 | }
84 |
85 | public static byte[] bitwiseOrByteArrays(byte[] arr0, byte[] arr1) {
86 | byte[] returnArray = new byte[arr0.length];
87 |
88 | for (int i = 0; i < arr0.length; i++) {
89 | returnArray[i] = (byte) (arr0[i] | arr1[i]);
90 | }
91 |
92 | return returnArray;
93 | }
94 |
95 | public static byte[] bitwiseAndByteArrays(byte[] arr0, byte[] arr1) {
96 | byte[] returnArray = new byte[arr0.length];
97 |
98 | for (int i = 0; i < arr0.length; i++) {
99 | returnArray[i] = (byte) (arr0[i] & arr1[i]);
100 | }
101 |
102 | return returnArray;
103 | }
104 |
105 | public static byte[] inverseByteArrayBits(byte[] arr0) {
106 | byte[] returnArray = new byte[arr0.length];
107 |
108 | for (int i = 0; i < arr0.length; i++) {
109 | returnArray[i] = (byte) ~arr0[i];
110 | }
111 |
112 | return returnArray;
113 | }
114 |
115 | public static boolean isByteArrayEmpty(byte[] bytes) {
116 | for (int i = 0; i < bytes.length; i++) {
117 | if (bytes[i] != 0x00) {
118 | return false;
119 | }
120 | }
121 |
122 | return true;
123 | }
124 |
125 | public static boolean isBitSet(byte[] arr, int bit) {
126 | int index = bit / 8; // Get the index of the array for the byte with this bit
127 | int bitPosition = bit % 8; // Position of this bit in a byte
128 |
129 | return (arr[index] >> bitPosition & 1) == 1;
130 | }
131 |
132 | public static void setBit(byte[] arr, int bit) {
133 | int index = bit / 8; // Get the index of the array for the byte with this bit
134 | int bitPosition = bit % 8; // Position of this bit in a byte
135 |
136 | arr[index] = (byte) (arr[index] | (1 << bitPosition));
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/transport_manager/gateway_connection/LFXGatewayConnection.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXGatewayConnection.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.transport_manager.gateway_connection;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.entities.internal.LFXGatewayDescriptor;
14 | import lifx.java.android.entities.internal.LFXMessage;
15 | import lifx.java.android.entities.internal.structle.LxProtocol;
16 | import lifx.java.android.entities.internal.structle.LxProtocol.Type;
17 |
18 | public abstract class LFXGatewayConnection {
19 | private static ArrayList permittedMessageTypes;
20 |
21 | static {
22 | permittedMessageTypes = new ArrayList();
23 | permittedMessageTypes.add(Type.LX_PROTOCOL_LIGHT_SET);
24 | permittedMessageTypes.add(Type.LX_PROTOCOL_LIGHT_SET_DIM_ABSOLUTE);
25 | permittedMessageTypes.add(Type.LX_PROTOCOL_DEVICE_SET_POWER);
26 | permittedMessageTypes.add(Type.LX_PROTOCOL_LIGHT_GET);
27 | permittedMessageTypes.add(Type.LX_PROTOCOL_LIGHT_SET_WAVEFORM);
28 | permittedMessageTypes.add(Type.LX_PROTOCOL_DEVICE_GET_MESH_FIRMWARE);
29 | permittedMessageTypes.add(Type.LX_PROTOCOL_DEVICE_GET_WIFI_FIRMWARE);
30 | permittedMessageTypes.add(Type.LX_PROTOCOL_DEVICE_GET_VERSION);
31 | }
32 |
33 | public enum LFXGatewayConnectionState {
34 | NOT_CONNECTED,
35 | CONNECTING,
36 | CONNECTED,
37 | }
38 |
39 |
40 | public static LFXGatewayConnection getGatewayConnectionWithGatewayDescriptor(LFXGatewayDescriptor gatewayDescriptor, LFXGatewayConnectionListener listener) {
41 | // TODO: implement TCP
42 |
43 | switch (gatewayDescriptor.getService()) {
44 | case LX_PROTOCOL_DEVICE_SERVICE_TCP:
45 | break;
46 | case LX_PROTOCOL_DEVICE_SERVICE_UDP:
47 | return new LFXUDPGatewayConnection(gatewayDescriptor, listener);
48 | default:
49 | break;
50 | }
51 |
52 | return null;
53 | }
54 |
55 | public LFXGatewayConnection(LFXGatewayDescriptor gatewayDescriptor, LFXGatewayConnectionListener listener) {
56 | this.gatewayDescriptor = gatewayDescriptor;
57 | this.listener = listener;
58 | }
59 |
60 | private LFXGatewayDescriptor gatewayDescriptor;
61 |
62 | public LFXGatewayDescriptor getGatewayDescriptor() {
63 | return gatewayDescriptor;
64 | }
65 |
66 | private LFXGatewayConnectionListener listener;
67 |
68 | // Connection State
69 | public abstract void connect();
70 |
71 | public abstract void disconnect();
72 |
73 | private LFXGatewayConnectionState connectionState;
74 |
75 | public LFXGatewayConnectionState getConnectionState() {
76 | return connectionState;
77 | }
78 |
79 | protected void setConnectionState(LFXGatewayConnectionState connectionState) {
80 | this.connectionState = connectionState;
81 | }
82 |
83 | protected LFXGatewayConnectionListener getListener() {
84 | return listener;
85 | }
86 |
87 | public void setListener(LFXGatewayConnectionListener listener) {
88 | this.listener = listener;
89 | }
90 |
91 | // To be called externally (subclasses to override)
92 | public abstract void sendMessage(LFXMessage message);
93 |
94 | // temp hack for OTA work
95 | public abstract void sendData(byte[] data);
96 |
97 | public interface LFXGatewayConnectionListener {
98 | public void gatewayConnectionDidReceiveMessageFromHost(LFXGatewayConnection connection, LFXMessage message, String host);
99 |
100 | public void gatewayConnectionDidConnect(LFXGatewayConnection connection);
101 |
102 | public void gatewayConnectionDidDisconnectWithError(LFXGatewayConnection connection, String error);
103 | }
104 |
105 | public String getConnectionStateString() {
106 | return this.connectionState.toString();
107 | }
108 |
109 | // For subclasses to use when queueing messages in an outbox
110 | protected static boolean newMessageMakesQueuedMessageRedundant(LFXMessage newMessage, LFXMessage queuedMessage) {
111 | if (newMessage.getType() != queuedMessage.getType()) // if the message types are not equal
112 | {
113 | return false;
114 | }
115 |
116 | if (!newMessage.getPath().equals(queuedMessage.getPath())) // if the message paths are not equal
117 | {
118 | return false;
119 | }
120 |
121 | // TODO:
122 | // if( !permittedMessageTypes.contains( newMessage.getType()))
123 | // {
124 | // return false;
125 | // }
126 |
127 | return true;
128 | }
129 |
130 | }
131 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/util/LFXNetworkUtils.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXNetworkUtils.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.util;
10 |
11 | import java.net.InetAddress;
12 | import java.net.NetworkInterface;
13 | import java.net.UnknownHostException;
14 | import java.util.Collections;
15 | import java.util.List;
16 |
17 | import org.apache.http.conn.util.InetAddressUtils;
18 |
19 | import android.annotation.SuppressLint;
20 | import android.content.Context;
21 | import android.net.DhcpInfo;
22 | import android.net.wifi.WifiManager;
23 |
24 | public class LFXNetworkUtils {
25 | private final static String TAG = LFXNetworkUtils.class.getSimpleName();
26 |
27 | @SuppressLint("DefaultLocale")
28 | public static String getLocalHostAddress() {
29 | boolean useIPv4 = true;
30 |
31 | try {
32 | List interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
33 | for (NetworkInterface intf : interfaces) {
34 | List addrs = Collections.list(intf.getInetAddresses());
35 | for (InetAddress addr : addrs) {
36 | if (!addr.isLoopbackAddress()) {
37 | String sAddr = addr.getHostAddress().toUpperCase();
38 | boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
39 | if (useIPv4) {
40 | if (isIPv4) {
41 | return sAddr;
42 | }
43 | } else {
44 | if (!isIPv4) {
45 | int delim = sAddr.indexOf('%'); // drop ip6 port suffix
46 | return delim < 0 ? sAddr : sAddr.substring(0, delim);
47 | }
48 | }
49 | }
50 | }
51 | }
52 | } catch (Exception ex) {
53 | } // for now eat exceptions
54 | return "";
55 | }
56 |
57 |
58 | // public static String getBroadcastAddress()
59 | // {
60 | // return "255.255.255.255";
61 | // }
62 |
63 | // public static String getBroadcastAddress()
64 | // {
65 | // String found_bcast_address = null;
66 | // System.setProperty( "java.net.preferIPv4Stack", "true");
67 | //
68 | // try
69 | // {
70 | // Enumeration niEnum = NetworkInterface.getNetworkInterfaces();
71 | // while( niEnum.hasMoreElements())
72 | // {
73 | // NetworkInterface ni = niEnum.nextElement();
74 | //
75 | // Enumeration iNetAddresses = ni.getInetAddresses();
76 | // while( iNetAddresses.hasMoreElements())
77 | // {
78 | // InetAddress i = iNetAddresses.nextElement();
79 | // System.out.println( "Address: " + i.getHostAddress());
80 | // }
81 | //
82 | // if( !ni.isLoopback())
83 | // {
84 | // for( InterfaceAddress interfaceAddress : ni.getInterfaceAddresses())
85 | // {
86 | // if( interfaceAddress.getBroadcast() != null)
87 | // {
88 | // found_bcast_address = interfaceAddress.getBroadcast().toString();
89 | // found_bcast_address = found_bcast_address.substring( 1);
90 | // }
91 | // else
92 | // {
93 | // System.out.println( "Found bcast address: " + interfaceAddress.toString());
94 | // }
95 | // }
96 | // }
97 | // }
98 | // }
99 | // catch( SocketException e)
100 | // {
101 | // e.printStackTrace();
102 | // }
103 | //
104 | // return found_bcast_address;
105 | // }
106 |
107 | public static String getBroadcastAddress(Context context) {
108 | WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
109 | DhcpInfo dhcp = wifi.getDhcpInfo();
110 |
111 | int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
112 | byte[] quads = new byte[4];
113 | for (int k = 0; k < 4; k++)
114 | quads[k] = (byte) (broadcast >> (k * 8));
115 | try {
116 | return InetAddress.getByAddress(quads).getHostAddress();
117 | } catch (UnknownHostException e) {
118 | e.printStackTrace();
119 | }
120 |
121 | return "255.255.255.255";
122 | }
123 |
124 | public static String getIPv4StringByStrippingIPv6Prefix(String in) {
125 | String ipv6Prefix = "::ffff:";
126 |
127 | if (in.startsWith(ipv6Prefix)) {
128 | return in.substring(ipv6Prefix.length(), in.length());
129 | }
130 |
131 | return in;
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/light/LFXTaggedLightCollection.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXTaggedLightCollection.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.light;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.entities.LFXHSBKColor;
14 | import lifx.java.android.entities.LFXTypes.LFXPowerState;
15 | import lifx.java.android.entities.internal.LFXBinaryTypes;
16 | import lifx.java.android.entities.internal.LFXMessage;
17 | import lifx.java.android.entities.internal.LFXTarget;
18 | import lifx.java.android.entities.internal.LFXTarget.LFXTargetType;
19 | import lifx.java.android.entities.internal.structle.LxProtocolDevice;
20 | import lifx.java.android.entities.internal.structle.LxProtocolLight;
21 | import lifx.java.android.entities.internal.structle.LxProtocol.Type;
22 | import lifx.java.android.entities.internal.structle.LxProtocolLight.Hsbk;
23 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt16;
24 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt32;
25 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt8;
26 | import lifx.java.android.light.LFXLight.LFXLightListener;
27 | import lifx.java.android.network_context.LFXNetworkContext;
28 |
29 | public class LFXTaggedLightCollection extends LFXLightCollection implements LFXLightListener {
30 | private final static String TAG=LFXTaggedLightCollection.class.getSimpleName();
31 |
32 | public static LFXTaggedLightCollection getLightCollectionWithNetworkContext(LFXNetworkContext networkContext) {
33 | LFXTaggedLightCollection collection = new LFXTaggedLightCollection();
34 | collection.networkContext = networkContext;
35 | collection.lights = new ArrayList();
36 | return collection;
37 | }
38 |
39 | private String tag;
40 |
41 | //private LFXTarget target;
42 |
43 | public String getTag() {
44 | return tag;
45 | }
46 |
47 | public LFXTargetType getTargetType() {
48 | return LFXTargetType.TAG;
49 | }
50 |
51 | public LFXTarget getTarget() {
52 | return LFXTarget.getTagTargetWithTag(tag);
53 | }
54 |
55 | public void addLight(LFXLight light) {
56 | super.addLight(light);
57 | networkContext.addLightToTaggedLightCollection(light, this);
58 | }
59 |
60 | public void removeLight(LFXLight light) {
61 | super.removeLight(light);
62 | networkContext.removeLightFromTaggedLightCollection(light, this);
63 | }
64 |
65 | public void removeAllLights() {
66 | for (LFXLight aLight : getLights()) {
67 | removeLight(aLight);
68 | }
69 | }
70 |
71 | // Getters
72 | public String getLabel() {
73 | return tag;
74 | }
75 |
76 | // Setters
77 | @Override
78 | public void setColor(LFXHSBKColor color) {
79 | super.setColor(color);
80 | setColorOverDuration(color, 250);
81 | }
82 |
83 | public void setColorOverDuration(LFXHSBKColor color, long duration) {
84 | super.setColorOverDuration(color, duration);
85 | LFXMessage lightSet = LFXMessage.messageWithTypeAndTarget(Type.LX_PROTOCOL_LIGHT_SET, getTarget());
86 | Object padding = new Object();
87 | UInt8 stream = new UInt8(0);
88 | Hsbk protocolColor = LFXBinaryTypes.getLXProtocolLightHsbkFromLFXHSBKColor(color);
89 | UInt32 protocolDuration = new UInt32(duration);
90 | LxProtocolLight.Set payload = new LxProtocolLight.Set(padding, stream, protocolColor, protocolDuration);
91 | lightSet.setPayload(payload);
92 | networkContext.sendMessage(lightSet);
93 | }
94 |
95 | @Override
96 | public void setPowerState(LFXPowerState powerState) {
97 | //super.setPowerState( color, duration);
98 | LFXMessage setPower = LFXMessage.messageWithTypeAndTarget(Type.LX_PROTOCOL_DEVICE_SET_POWER, getTarget());
99 | Object padding = new Object();
100 | UInt16 protocolPowerLevel = LFXBinaryTypes.getLFXProtocolPowerLevelFromLFXPowerState(powerState);
101 | LxProtocolDevice.SetPower payload = new LxProtocolDevice.SetPower(padding, protocolPowerLevel);
102 | setPower.setPayload(payload);
103 | networkContext.sendMessage(setPower);
104 | }
105 |
106 | @Override
107 | public void setLabel(String label) {
108 | networkContext.renameTaggedLightCollectionWithNewTag(this, label);
109 | }
110 |
111 | public void setTag(String tag) {
112 | this.tag = tag;
113 | }
114 |
115 | @Override
116 | public void lightDidChangeLabel(LFXLight light, String label) {
117 | }
118 |
119 | @Override
120 | public void lightDidChangeColor(LFXLight light, LFXHSBKColor color) {
121 | }
122 |
123 | @Override
124 | public void lightDidChangePowerState(LFXLight light, LFXPowerState powerState) {
125 | }
126 |
127 | @Override
128 | public void handleMessage(LFXMessage message) {
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/transport_manager/LFXTransportManager.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXTransportManager.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.transport_manager;
10 |
11 | import java.util.ArrayList;
12 | import lifx.java.android.entities.internal.LFXGatewayDescriptor;
13 | import lifx.java.android.entities.internal.LFXMessage;
14 | import lifx.java.android.entities.internal.LFXMessageObservationDescriptor;
15 | import lifx.java.android.entities.internal.LFXSiteID;
16 | import lifx.java.android.entities.internal.LFXMessageObservationDescriptor.LFXMessageObserverCallback;
17 | import lifx.java.android.network_context.LFXNetworkContext;
18 |
19 | public abstract class LFXTransportManager
20 | {
21 | public interface LFXTransportManagerListener
22 | {
23 | public void transportManagerDidConnect( LFXTransportManager transportManager);
24 | public void transportManagerDidDisconnect( LFXTransportManager transportManager);
25 |
26 | public void transportManagerDidConnectToGateway( LFXTransportManager transportManager, LFXGatewayDescriptor gatewayDescriptor);
27 | public void transportManagerDidDisconnectFromGateway( LFXTransportManager transportManager, LFXGatewayDescriptor gatewayDescriptor);
28 | }
29 |
30 | private LFXNetworkContext networkContext;
31 | protected LFXTransportManagerListener listener;
32 |
33 | // May have no meaning for some Network Contexts
34 | public abstract void connect();
35 |
36 | public abstract void disconnect();
37 |
38 | private boolean isConnected;
39 |
40 | // After sending, -sendObserverCallbacksForMessage: should be called with the message.
41 | public abstract void sendMessage( LFXMessage message);
42 |
43 | public void setNetworkContext( LFXNetworkContext networkContext)
44 | {
45 | this.networkContext = networkContext;
46 | }
47 |
48 | public void setListener( LFXTransportManagerListener listener)
49 | {
50 | this.listener = listener;
51 | }
52 |
53 | // Token Based subscriptions
54 | // - (id)addMessageObserverWithCallback:(LFXMessageObserverCallback)callback; // returns an observer "token"
55 | // - (void)removeMessageObserverToken:(id)observerToken; // This will remove the single observation created with the above method
56 | // public Object addMessageObserverWithCallback( LFXMessageObserverCallback callback);
57 | // public void removeMessageObserverToken( Object observerToken);
58 |
59 | // Observer Based subscriptions
60 | // - (void)addMessageObserverObject:(id)observingObject withCallback:(LFXMessageObserverCallback)callback;
61 | // - (void)removeMessageObserversForObject:(id)anObserverObject; // This will remove all observations created with the above method
62 | // public void addMessageObserverObjectWithCallback( Object observerObject, LFXMessageObserverCallback callback);
63 | // public void removeMessageObserversForObject( Object anObserverObject);
64 |
65 | // This should be called (not overidden) for every incoming _and_ outgoing message
66 | //- (void)sendObserverCallbacksForMessage:(LFXMessage *)message;
67 | // public void sendObserverCallbacksForMessage( LFXMessage message);
68 |
69 | // This is used by the Network Context to work out what exact messages should be sent
70 |
71 | private ArrayList visibleSiteIDs;
72 | private ArrayList observationDescriptors;
73 |
74 | public LFXTransportManager()
75 | {
76 | super();
77 | observationDescriptors = new ArrayList();
78 | }
79 |
80 | public boolean isConnected()
81 | {
82 | return isConnected;
83 | }
84 |
85 | public void setIsConnected( boolean isConnected)
86 | {
87 | if( isConnected() == isConnected)
88 | {
89 | return;
90 | }
91 |
92 | if( isConnected)
93 | {
94 | listener.transportManagerDidConnect( this);
95 | }
96 | else
97 | {
98 | listener.transportManagerDidDisconnect( this);
99 | }
100 |
101 | this.isConnected = isConnected;
102 | }
103 |
104 | // Token Based subscriptions
105 | public Object addMessageObserverWithCallback( LFXMessageObserverCallback callback)
106 | {
107 | LFXMessageObservationDescriptor observationDescriptor = new LFXMessageObservationDescriptor();
108 | observationDescriptor.setCallback( callback);
109 | observationDescriptors.add( observationDescriptor);
110 | return observationDescriptor;
111 | }
112 |
113 | public void removeMessageObserverToken( Object observerToken)
114 | {
115 | observationDescriptors.remove( observerToken);
116 | }
117 |
118 | // Observer Based subscriptions
119 | public void addMessageObserverObjectWithCallback( Object observingObject, LFXMessageObserverCallback callback)
120 | {
121 | LFXMessageObservationDescriptor observationDescriptor = new LFXMessageObservationDescriptor();
122 | observationDescriptor.setCallback( callback);
123 | observationDescriptor.setObservingObject( observingObject);
124 | observationDescriptors.add( observationDescriptor);
125 | }
126 |
127 | @SuppressWarnings( "unchecked")
128 | public void removeMessageObserversForObject( Object anObserverObject)
129 | {
130 | for( LFXMessageObservationDescriptor observationDescriptor : (ArrayList) observationDescriptors.clone())
131 | {
132 | if( observationDescriptor.observingObjectWasEqualTo( anObserverObject))
133 | {
134 | observationDescriptors.remove( observationDescriptor);
135 | }
136 | }
137 | }
138 |
139 | @SuppressWarnings( "unchecked")
140 | public void sendObserverCallbacksForMessage( LFXMessage message)
141 | {
142 | for( LFXMessageObservationDescriptor observationDescriptor : (ArrayList) observationDescriptors.clone())
143 | {
144 | observationDescriptor.getCallback().run( observationDescriptor.getObservingObject(), message);
145 | }
146 | }
147 |
148 | public ArrayList getVisibleSiteIDs()
149 | {
150 | return visibleSiteIDs;
151 | }
152 |
153 | public LFXNetworkContext getNetworkContext()
154 | {
155 | return networkContext;
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/examples/src/com/example/lifx_sdk_samples/LFXSDKLightRandomColorActivity.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSDKLightRandomColorActivity.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package com.example.lifx_sdk_samples;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.client.LFXClient;
14 | import lifx.java.android.entities.LFXHSBKColor;
15 | import lifx.java.android.entities.LFXTypes.LFXFuzzyPowerState;
16 | import lifx.java.android.entities.LFXTypes.LFXPowerState;
17 | import lifx.java.android.light.LFXLight;
18 | import lifx.java.android.light.LFXLight.LFXLightListener;
19 | import lifx.java.android.light.LFXLightCollection;
20 | import lifx.java.android.light.LFXLightCollection.LFXLightCollectionListener;
21 | import lifx.java.android.light.LFXTaggedLightCollection;
22 | import lifx.java.android.network_context.LFXNetworkContext;
23 | import lifx.java.android.network_context.LFXNetworkContext.LFXNetworkContextListener;
24 | import android.os.Bundle;
25 | import android.app.Activity;
26 | import android.view.Menu;
27 | import android.view.View;
28 | import android.widget.AdapterView;
29 | import android.widget.AdapterView.OnItemClickListener;
30 | import android.widget.ListView;
31 | import android.widget.Toast;
32 |
33 | public class LFXSDKLightRandomColorActivity extends Activity implements LFXLightListener, LFXLightCollectionListener, LFXNetworkContextListener
34 | {
35 | private LFXNetworkContext networkContext;
36 | private LFXSDKLightListAdapter lightListAdapter;
37 | private LFXSDKTaggedLightCollectionListAdapter groupListAdapter;
38 |
39 | @Override
40 | protected void onCreate( Bundle savedInstanceState)
41 | {
42 | super.onCreate( savedInstanceState);
43 | setContentView( R.layout.lifx_list_sample_layout);
44 |
45 | networkContext = LFXClient.getSharedInstance( getApplicationContext()).getLocalNetworkContext();
46 | networkContext.addNetworkContextListener( this);
47 | networkContext.getAllLightsCollection().addLightCollectionListener( this);
48 |
49 | ListView lightListView = (ListView) findViewById( R.id.light_list_view);
50 | lightListAdapter = new LFXSDKLightListAdapter( this);
51 | lightListView.setAdapter( lightListAdapter);
52 |
53 | ListView groupListView = (ListView) findViewById( R.id.group_list_view);
54 | groupListAdapter = new LFXSDKTaggedLightCollectionListAdapter( this);
55 | groupListView.setAdapter( groupListAdapter);
56 |
57 | updateStateFromLIFX();
58 |
59 | lightListView.setOnItemClickListener( new OnItemClickListener()
60 | {
61 | @Override
62 | public void onItemClick( AdapterView> arg0, View arg1, int position, long arg3)
63 | {
64 | LFXLight light = (LFXLight) lightListAdapter.getItem( position);
65 |
66 | LFXHSBKColor color = LFXHSBKColor.getColor( (float) (Math.random() * 360), 1.0f, 1.0f, 3500);
67 | light.setColor( color);
68 | }
69 | });
70 |
71 | groupListView.setOnItemClickListener( new OnItemClickListener()
72 | {
73 | @Override
74 | public void onItemClick( AdapterView> arg0, View arg1, int position, long arg3)
75 | {
76 | LFXTaggedLightCollection lightCollection = (LFXTaggedLightCollection) groupListAdapter.getItem( position);
77 |
78 | LFXHSBKColor color = LFXHSBKColor.getColor( (float) (Math.random() * 360), 1.0f, 1.0f, 3500);
79 | lightCollection.setColor( color);
80 | }
81 | });
82 | }
83 |
84 | @Override
85 | public boolean onCreateOptionsMenu( Menu menu)
86 | {
87 | getMenuInflater().inflate( R.menu.sample, menu);
88 | return true;
89 | }
90 |
91 | @Override
92 | protected void onPause()
93 | {
94 | networkContext.removeNetworkContextListener( this);
95 | super.onPause();
96 | }
97 |
98 | private void updateStateFromLIFX()
99 | {
100 | ArrayList allLights = networkContext.getAllLightsCollection().getLights();
101 | lightListAdapter.updateWithLights( allLights);
102 |
103 | ArrayList lightCollections = networkContext.getTaggedLightCollections();
104 | groupListAdapter.updateWithLightCollections( lightCollections);
105 | }
106 |
107 | @Override
108 | public void networkContextDidConnect( LFXNetworkContext networkContext)
109 | {
110 | Toast toast = Toast.makeText( this, "CONNECTED", Toast.LENGTH_SHORT);
111 | toast.show();
112 | }
113 |
114 | @Override
115 | public void networkContextDidDisconnect( LFXNetworkContext networkContext)
116 | {
117 | Toast toast = Toast.makeText( this, "DISCONNECTED", Toast.LENGTH_SHORT);
118 | toast.show();
119 | }
120 |
121 | @Override
122 | public void networkContextDidAddTaggedLightCollection( LFXNetworkContext networkContext, LFXTaggedLightCollection collection)
123 | {
124 | updateStateFromLIFX();
125 | }
126 |
127 | @Override
128 | public void networkContextDidRemoveTaggedLightCollection( LFXNetworkContext networkContext, LFXTaggedLightCollection collection)
129 | {
130 | updateStateFromLIFX();
131 | }
132 |
133 | @Override
134 | public void lightCollectionDidAddLight( LFXLightCollection lightCollection, LFXLight light)
135 | {
136 | updateStateFromLIFX();
137 | light.addLightListener( this);
138 | }
139 |
140 | @Override
141 | public void lightCollectionDidRemoveLight( LFXLightCollection lightCollection, LFXLight light)
142 | {
143 | updateStateFromLIFX();
144 | light.removeLightListener( this);
145 | }
146 |
147 | @Override
148 | public void lightCollectionDidChangeLabel( LFXLightCollection lightCollection, String label) {}
149 |
150 | @Override
151 | public void lightCollectionDidChangeColor( LFXLightCollection lightCollection, LFXHSBKColor color) {}
152 |
153 | @Override
154 | public void lightCollectionDidChangeFuzzyPowerState( LFXLightCollection lightCollection, LFXFuzzyPowerState fuzzyPowerState) {}
155 |
156 | @Override
157 | public void lightDidChangeLabel( LFXLight light, String label)
158 | {
159 | updateStateFromLIFX();
160 | }
161 |
162 | @Override
163 | public void lightDidChangeColor( LFXLight light, LFXHSBKColor color)
164 | {
165 | updateStateFromLIFX();
166 | }
167 |
168 | @Override
169 | public void lightDidChangePowerState( LFXLight light, LFXPowerState powerState)
170 | {
171 | updateStateFromLIFX();
172 | }
173 | }
174 |
--------------------------------------------------------------------------------
/examples/src/com/example/lifx_sdk_samples/LFXSDKLightPowerActivity.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSDKLightPowerActivity.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package com.example.lifx_sdk_samples;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.client.LFXClient;
14 | import lifx.java.android.entities.LFXHSBKColor;
15 | import lifx.java.android.entities.LFXTypes.LFXFuzzyPowerState;
16 | import lifx.java.android.entities.LFXTypes.LFXPowerState;
17 | import lifx.java.android.light.LFXLight;
18 | import lifx.java.android.light.LFXLight.LFXLightListener;
19 | import lifx.java.android.light.LFXLightCollection;
20 | import lifx.java.android.light.LFXLightCollection.LFXLightCollectionListener;
21 | import lifx.java.android.light.LFXTaggedLightCollection;
22 | import lifx.java.android.network_context.LFXNetworkContext;
23 | import lifx.java.android.network_context.LFXNetworkContext.LFXNetworkContextListener;
24 | import android.os.Bundle;
25 | import android.app.Activity;
26 | import android.view.Menu;
27 | import android.view.View;
28 | import android.widget.AdapterView;
29 | import android.widget.AdapterView.OnItemClickListener;
30 | import android.widget.ListView;
31 | import android.widget.Toast;
32 |
33 | public class LFXSDKLightPowerActivity extends Activity implements LFXLightListener, LFXLightCollectionListener, LFXNetworkContextListener
34 | {
35 | private LFXNetworkContext networkContext;
36 | private LFXSDKLightListAdapter lightListAdapter;
37 | private LFXSDKTaggedLightCollectionListAdapter groupListAdapter;
38 |
39 | @Override
40 | protected void onCreate( Bundle savedInstanceState)
41 | {
42 | super.onCreate( savedInstanceState);
43 | setContentView( R.layout.lifx_list_sample_layout);
44 |
45 | networkContext = LFXClient.getSharedInstance( getApplicationContext()).getLocalNetworkContext();
46 | networkContext.addNetworkContextListener( this);
47 | networkContext.getAllLightsCollection().addLightCollectionListener( this);
48 |
49 | ListView lightListView = (ListView) findViewById( R.id.light_list_view);
50 | lightListAdapter = new LFXSDKLightListAdapter( this);
51 | lightListView.setAdapter( lightListAdapter);
52 |
53 | ListView groupListView = (ListView) findViewById( R.id.group_list_view);
54 | groupListAdapter = new LFXSDKTaggedLightCollectionListAdapter( this);
55 | groupListView.setAdapter( groupListAdapter);
56 |
57 | updateStateFromLIFX();
58 |
59 | lightListView.setOnItemClickListener( new OnItemClickListener()
60 | {
61 | @Override
62 | public void onItemClick( AdapterView> arg0, View arg1, int position, long arg3)
63 | {
64 | LFXLight light = (LFXLight) lightListAdapter.getItem( position);
65 |
66 | if( light.getPowerState() == LFXPowerState.ON)
67 | {
68 | light.setPowerState( LFXPowerState.OFF);
69 | }
70 | else
71 | {
72 | light.setPowerState( LFXPowerState.ON);
73 | }
74 | }
75 | });
76 |
77 | groupListView.setOnItemClickListener( new OnItemClickListener()
78 | {
79 | @Override
80 | public void onItemClick( AdapterView> arg0, View arg1, int position, long arg3)
81 | {
82 | LFXLightCollection lightCollection = (LFXLightCollection) groupListAdapter.getItem( position);
83 |
84 | if( lightCollection.getFuzzyPowerState() == LFXFuzzyPowerState.ON)
85 | {
86 | lightCollection.setPowerState( LFXPowerState.OFF);
87 | }
88 | else
89 | {
90 | lightCollection.setPowerState( LFXPowerState.ON);
91 | }
92 | }
93 | });
94 | }
95 |
96 | @Override
97 | public boolean onCreateOptionsMenu( Menu menu)
98 | {
99 | getMenuInflater().inflate( R.menu.sample, menu);
100 | return true;
101 | }
102 |
103 | @Override
104 | protected void onPause()
105 | {
106 | networkContext.removeNetworkContextListener( this);
107 | super.onPause();
108 | }
109 |
110 | private void updateStateFromLIFX()
111 | {
112 | ArrayList allLights = networkContext.getAllLightsCollection().getLights();
113 | lightListAdapter.updateWithLights( allLights);
114 |
115 | ArrayList lightCollections = networkContext.getTaggedLightCollections();
116 | groupListAdapter.updateWithLightCollections( lightCollections);
117 | }
118 |
119 | @Override
120 | public void networkContextDidConnect( LFXNetworkContext networkContext)
121 | {
122 | Toast toast = Toast.makeText( this, "CONNECTED", Toast.LENGTH_SHORT);
123 | toast.show();
124 | }
125 |
126 | @Override
127 | public void networkContextDidDisconnect( LFXNetworkContext networkContext)
128 | {
129 | Toast toast = Toast.makeText( this, "DISCONNECTED", Toast.LENGTH_SHORT);
130 | toast.show();
131 | }
132 |
133 | @Override
134 | public void networkContextDidAddTaggedLightCollection( LFXNetworkContext networkContext, LFXTaggedLightCollection collection)
135 | {
136 | updateStateFromLIFX();
137 | }
138 |
139 | @Override
140 | public void networkContextDidRemoveTaggedLightCollection( LFXNetworkContext networkContext, LFXTaggedLightCollection collection)
141 | {
142 | updateStateFromLIFX();
143 | }
144 |
145 | @Override
146 | public void lightCollectionDidAddLight( LFXLightCollection lightCollection, LFXLight light)
147 | {
148 | updateStateFromLIFX();
149 | light.addLightListener( this);
150 | }
151 |
152 | @Override
153 | public void lightCollectionDidRemoveLight( LFXLightCollection lightCollection, LFXLight light)
154 | {
155 | updateStateFromLIFX();
156 | light.removeLightListener( this);
157 | }
158 |
159 | @Override
160 | public void lightCollectionDidChangeLabel( LFXLightCollection lightCollection, String label) {}
161 |
162 | @Override
163 | public void lightCollectionDidChangeColor( LFXLightCollection lightCollection, LFXHSBKColor color) {}
164 |
165 | @Override
166 | public void lightCollectionDidChangeFuzzyPowerState( LFXLightCollection lightCollection, LFXFuzzyPowerState fuzzyPowerState) {}
167 |
168 | @Override
169 | public void lightDidChangeLabel( LFXLight light, String label)
170 | {
171 | updateStateFromLIFX();
172 | }
173 |
174 | @Override
175 | public void lightDidChangeColor( LFXLight light, LFXHSBKColor color)
176 | {
177 | updateStateFromLIFX();
178 | }
179 |
180 | @Override
181 | public void lightDidChangePowerState( LFXLight light, LFXPowerState powerState)
182 | {
183 | updateStateFromLIFX();
184 | }
185 | }
186 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/light/LFXLightCollection.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXLightCollection.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.light;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.entities.LFXHSBKColor;
14 | import lifx.java.android.entities.LFXLightTarget;
15 | import lifx.java.android.entities.LFXTypes.LFXFuzzyPowerState;
16 | import lifx.java.android.entities.LFXTypes.LFXPowerState;
17 | import lifx.java.android.entities.internal.LFXMessage;
18 | import lifx.java.android.entities.internal.LFXTarget;
19 | import lifx.java.android.entities.internal.LFXTarget.LFXTargetType;
20 | import lifx.java.android.light.LFXLight.LFXLightListener;
21 | import lifx.java.android.network_context.LFXNetworkContext;
22 |
23 | public abstract class LFXLightCollection extends LFXLightTarget implements LFXLightListener
24 | {
25 | public interface LFXLightCollectionListener
26 | {
27 | public void lightCollectionDidAddLight( LFXLightCollection lightCollection, LFXLight light);
28 | public void lightCollectionDidRemoveLight( LFXLightCollection lightCollection, LFXLight light);
29 |
30 | public void lightCollectionDidChangeLabel( LFXLightCollection lightCollection, String label);
31 | public void lightCollectionDidChangeColor( LFXLightCollection lightCollection, LFXHSBKColor color);
32 | public void lightCollectionDidChangeFuzzyPowerState( LFXLightCollection lightCollection, LFXFuzzyPowerState fuzzyPowerState);
33 | }
34 |
35 | protected LFXNetworkContext networkContext;
36 |
37 | private ArrayList listeners = new ArrayList();
38 |
39 | protected ArrayList lights;
40 |
41 | // Light State
42 | public String label;
43 | public LFXHSBKColor color;
44 | public LFXFuzzyPowerState fuzzyPowerState;
45 |
46 | public LFXTarget getTarget()
47 | {
48 | return null;
49 | }
50 |
51 | public LFXTargetType getTargetType()
52 | {
53 | return LFXTargetType.TAG;
54 | }
55 |
56 | public LFXLight getLightWithDeviceID( String deviceID)
57 | {
58 | for( LFXLight aLight : lights)
59 | {
60 | if( aLight.getDeviceID().equals( deviceID))
61 | {
62 | return aLight;
63 | }
64 | }
65 | return null;
66 | }
67 |
68 | @SuppressWarnings( "unchecked")
69 | public ArrayList getLights()
70 | {
71 | return (ArrayList) lights.clone();
72 | }
73 |
74 | // Light State
75 | public String getLabel()
76 | {
77 | return null;
78 | }
79 |
80 | public LFXHSBKColor getColor()
81 | {
82 | LFXHSBKColor[] lightColors = new LFXHSBKColor[lights.size()];
83 |
84 | for( int lightIndex = 0; lightIndex < lights.size(); lightIndex++)
85 | {
86 | lightColors[lightIndex] = lights.get( lightIndex).getColor();
87 | }
88 |
89 | return LFXHSBKColor.averageOfColors( lightColors);
90 | }
91 |
92 | public LFXFuzzyPowerState getFuzzyPowerState()
93 | {
94 | boolean isOn = false;
95 | boolean isOff = false;
96 | for( LFXLight aLight : lights)
97 | {
98 | if( aLight.getPowerState() == LFXPowerState.OFF)
99 | {
100 | isOff = true;
101 | }
102 |
103 | if( aLight.getPowerState() == LFXPowerState.ON)
104 | {
105 | isOn = true;
106 | }
107 | }
108 |
109 | if( isOn && isOff)
110 | {
111 | return LFXFuzzyPowerState.MIXED;
112 | }
113 |
114 | if( isOn)
115 | {
116 | return LFXFuzzyPowerState.ON;
117 | }
118 |
119 | if( isOff)
120 | {
121 | return LFXFuzzyPowerState.OFF;
122 | }
123 |
124 | return LFXFuzzyPowerState.OFF;
125 | }
126 |
127 |
128 | public LFXLight getFirstLightForLabel( String label)
129 | {
130 | for( LFXLight aLight : getLights())
131 | {
132 | if( aLight.getLabel() != null && aLight.getLabel().equals( label))
133 | {
134 | return aLight;
135 | }
136 | }
137 |
138 | return null;
139 | }
140 |
141 | public ArrayList getLightsForLabel( String label)
142 | {
143 | ArrayList lights = new ArrayList();
144 |
145 | for( LFXLight aLight : getLights())
146 | {
147 | if( aLight.getLabel() != null && aLight.getLabel().equals( label))
148 | {
149 | lights.add( aLight);
150 | }
151 | }
152 |
153 | return lights;
154 | }
155 |
156 | // Light Control
157 | public void setLabel( String label)
158 | {
159 | for( LFXLightCollectionListener aListener : listeners)
160 | {
161 | aListener.lightCollectionDidChangeLabel( this, label);
162 | }
163 | }
164 |
165 | public void setColor( LFXHSBKColor color)
166 | {
167 | }
168 |
169 | public void setColorOverDuration( LFXHSBKColor color, long duration)
170 | {
171 | for( LFXLightCollectionListener aListener : listeners)
172 | {
173 | aListener.lightCollectionDidChangeColor( this, color);
174 | }
175 | }
176 |
177 | public abstract void handleMessage( LFXMessage message);
178 |
179 | public void addLight( LFXLight light)
180 | {
181 | lights.add( light);
182 |
183 | for( LFXLightCollectionListener aListener : listeners)
184 | {
185 | aListener.lightCollectionDidAddLight( this, light);
186 | }
187 | }
188 |
189 | public void removeLight( LFXLight light)
190 | {
191 | lights.remove( light);
192 |
193 | for( LFXLightCollectionListener aListener : listeners)
194 | {
195 | aListener.lightCollectionDidRemoveLight( this, light);
196 | }
197 | }
198 |
199 | public void removeAllLights()
200 | {
201 | for( LFXLight aLight : lights)
202 | {
203 | for( LFXLightCollectionListener aListener : listeners)
204 | {
205 | aListener.lightCollectionDidRemoveLight( this, aLight);
206 | }
207 | }
208 |
209 | lights.clear();
210 | }
211 |
212 | public void addLightCollectionListener( LFXLightCollectionListener listener)
213 | {
214 | if( !listeners.contains( listener))
215 | {
216 | listeners.add( listener);
217 | }
218 | }
219 |
220 | public void removeAllLightCollectionListeners( LFXLightCollection lightCollection )
221 | {
222 | listeners.clear();
223 | }
224 |
225 | public void removeLightCollectionListener( LFXLightCollectionListener listener)
226 | {
227 | listeners.remove( listener);
228 | }
229 |
230 | @Override
231 | public void lightDidChangeLabel( LFXLight light, String label)
232 | {
233 |
234 | }
235 |
236 | @Override
237 | public void lightDidChangeColor( LFXLight light, LFXHSBKColor color)
238 | {
239 |
240 | }
241 |
242 | @Override
243 | public void lightDidChangePowerState( LFXLight light, LFXPowerState powerState)
244 | {
245 |
246 | }
247 | }
248 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/transport_manager/gateway_connection/LFXSocketUDP.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSocketUDP.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.transport_manager.gateway_connection;
10 |
11 | import java.net.DatagramPacket;
12 | import java.net.DatagramSocket;
13 | import java.net.InetAddress;
14 | import java.net.InetSocketAddress;
15 |
16 | import android.os.Handler;
17 | import android.os.Message;
18 |
19 | import lifx.java.android.util.LFXLog;
20 |
21 | public class LFXSocketUDP extends LFXSocketGeneric {
22 | private final static String TAG = LFXSocketUDP.class.getSimpleName();
23 | // Variables for receiving
24 | private Thread asyncReceiveThread;
25 |
26 | // Variables for sending
27 | private Thread asyncSendThread;
28 | public byte[] sendBuffer;
29 |
30 | private boolean isBroadcast = false;
31 | private byte[] broadcastIpAddress;
32 | private int broadcastPort;
33 |
34 | private DatagramSocket updSocket = null;
35 |
36 | public LFXSocketUDP() {
37 | super();
38 | LFXLog.d(TAG,"LFXSocketUDP() - Constructor");
39 | }
40 |
41 | public class MessageSendTask implements Runnable {
42 | private SocketMessage[] messages;
43 |
44 | public MessageSendTask(SocketMessage[] messages) {
45 | this.messages = messages;
46 | }
47 |
48 | @Override
49 | public void run() {
50 | for (SocketMessage message : messages) {
51 | DatagramSocket dataGramSocket = null;
52 |
53 | try {
54 | byte[] messageData = message.getMessageData();
55 |
56 | dataGramSocket = new DatagramSocket();
57 | dataGramSocket.setReuseAddress(true);
58 |
59 | DatagramPacket udpPacket;
60 |
61 | InetAddress ipAddress;
62 | int port;
63 |
64 | ipAddress = InetAddress.getByAddress(message.getIpAddress());
65 | port = message.getPort();
66 |
67 | udpPacket = new DatagramPacket(messageData, messageData.length, ipAddress, port);
68 |
69 | if (!dataGramSocket.isClosed()) {
70 | dataGramSocket.send(udpPacket);
71 | }
72 |
73 | }
74 | catch (Exception e) {
75 | e.printStackTrace();
76 | close();
77 | }
78 | finally {
79 | dataGramSocket.close();
80 | }
81 |
82 | }
83 | }
84 | }
85 |
86 | public void sendMessages(SocketMessage[] messages) {
87 | asyncSendThread = new Thread(new MessageSendTask(messages), "asyncSendThread");
88 | asyncSendThread.start();
89 | }
90 |
91 | private class UDPReceiveTask implements Runnable {
92 | private Handler handler;
93 |
94 | public UDPReceiveTask(Handler handler) {
95 | super();
96 | this.handler = handler;
97 | }
98 |
99 | public void publishProgress(SocketMessage[] messages) {
100 | Message msg = handler.obtainMessage();
101 | msg.what = SOCKET_RECEIVED_MESSAGE;
102 | msg.obj = messages[0];
103 | handler.sendMessage(msg);
104 | }
105 |
106 | public void publishConnected() {
107 | Message msg = handler.obtainMessage();
108 | msg.what = SOCKET_IS_CONNECTED;
109 | handler.sendMessage(msg);
110 | }
111 |
112 | public void publishConnecting() {
113 | Message msg = handler.obtainMessage();
114 | msg.what = SOCKET_IS_CONNECTING;
115 | handler.sendMessage(msg);
116 | }
117 |
118 | public void publishDisconnected() {
119 | Message msg = handler.obtainMessage();
120 | msg.what = SOCKET_IS_DISCONNECTED;
121 | handler.sendMessage(msg);
122 | }
123 |
124 | @Override
125 | public void run() {
126 | byte[] messageData = new byte[1024];
127 | DatagramPacket udpPacket = new DatagramPacket(messageData, messageData.length);
128 |
129 | try {
130 | boolean serverStarted = false;
131 |
132 | publishConnecting();
133 |
134 | InetAddress ipAddress = null;
135 | int port = 0;
136 |
137 | try {
138 | if (updSocket == null || updSocket.isClosed()) {
139 | updSocket = new DatagramSocket(null);
140 |
141 | if (isBroadcast) {
142 | ipAddress = InetAddress.getByAddress(broadcastIpAddress);
143 | port = broadcastPort;
144 | updSocket.setBroadcast(true);
145 | } else {
146 | ipAddress = InetAddress.getByAddress(getIpAddress());
147 | port = getPort();
148 | }
149 |
150 | updSocket.setReuseAddress(true);
151 | updSocket.bind(new InetSocketAddress(port));
152 |
153 | serverStarted = true;
154 | }
155 | } catch (Exception e) {
156 | e.printStackTrace();
157 | LFXLog.d(TAG, "UDPReceiveTask() - Error Starting server. IP: " + ipAddress.toString() + ", Port: " + port);
158 | updSocket = null;
159 | }
160 |
161 | LFXLog.d(TAG, "UDPReceiveTask() - UDP SOCKET MONITOR IS ONLINE - ip: " + ipAddress.toString() + ", port: " + port);
162 |
163 | if (serverStarted) {
164 | setServerRunning(true);
165 | publishConnected();
166 | } else {
167 | setServerRunning(false);
168 | }
169 |
170 | while (getServerRunning()) {
171 | updSocket.receive(udpPacket);
172 |
173 | byte[] messageAddress = udpPacket.getAddress().getAddress();
174 | int messagePort = udpPacket.getPort();
175 | SocketMessage message = new SocketMessage(messageData, messageAddress, messagePort);
176 |
177 | SocketMessage[] messages = new SocketMessage[]{message};
178 | publishProgress((SocketMessage[]) messages);
179 | }
180 | } catch (Exception e) {
181 | LFXLog.d(TAG, "UDPReceiveTask() - UDP Socket has been closed.");
182 | }
183 |
184 | close();
185 |
186 | publishDisconnected();
187 |
188 | LFXLog.d(TAG, "UDPReceiveTask() - UDP Socket Monitor Ended Execution.");
189 | }
190 | }
191 |
192 | @Override
193 | public void close() {
194 | LFXLog.d(TAG, "close()");
195 | super.close();
196 |
197 | if (updSocket != null) {
198 | updSocket.close();
199 | }
200 | }
201 |
202 | public void connect(byte[] ipAddress, int port) {
203 | bind(ipAddress, port);
204 |
205 | if (asyncReceiveThread == null || !asyncReceiveThread.isAlive()) {
206 | state = SocketState.CONNECTING;
207 | asyncReceiveThread = new Thread(new UDPReceiveTask(handler), "asyncReceiveThread");
208 | asyncReceiveThread.start();
209 | }
210 | }
211 |
212 | @Override
213 | public ConnectionType getConnectionType() {
214 | return ConnectionType.UDP;
215 | }
216 | }
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/transport_manager/gateway_connection/LFXSocketTCP.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSocketTCP.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.transport_manager.gateway_connection;
10 |
11 | import java.io.DataOutputStream;
12 | import java.io.IOException;
13 | import java.io.InputStream;
14 | import java.io.OutputStream;
15 | import java.net.InetAddress;
16 | import java.net.Socket;
17 |
18 | import android.os.Handler;
19 | import android.os.Message;
20 |
21 | import lifx.java.android.util.LFXLog;
22 |
23 | public class LFXSocketTCP extends LFXSocketGeneric {
24 | private final static String TAG = LFXSocketTCP.class.getSimpleName();
25 | private Thread asyncSocket;
26 | private Thread asyncSocketOutTask;
27 |
28 | private InputStream in;
29 | private OutputStream out;
30 |
31 | private Socket socket = null;
32 |
33 | public static final int RECEIVED_MESSAGE = 4;
34 | public static final int SOCKET_CONNECTION_FAILED = 5;
35 |
36 | // public LFXSocketTCP( byte[] ipAddress, int port)
37 | // {
38 | // super( ipAddress, port);
39 | // }
40 |
41 | public LFXSocketTCP() {
42 | super();
43 | LFXLog.d(TAG, "LFXSocketTCP() - Constructor");
44 | }
45 |
46 | private class TCPReceiveTask implements Runnable {
47 | private Handler handler;
48 |
49 | public TCPReceiveTask(Handler handler) {
50 | super();
51 | this.handler = handler;
52 | }
53 |
54 | public void publishProgress(SocketMessage[] messages) {
55 | Message msg = handler.obtainMessage();
56 | msg.what = SOCKET_RECEIVED_MESSAGE;
57 | msg.obj = messages[0];
58 | handler.sendMessage(msg);
59 | }
60 |
61 | public void publishConnected() {
62 | Message msg = handler.obtainMessage();
63 | msg.obj = SOCKET_IS_CONNECTED;
64 | handler.sendMessage(msg);
65 | }
66 |
67 | public void publishConnecting() {
68 | Message msg = handler.obtainMessage();
69 | msg.obj = SOCKET_IS_CONNECTING;
70 | handler.sendMessage(msg);
71 | }
72 |
73 | public void publishDisconnected() {
74 | Message msg = handler.obtainMessage();
75 | msg.obj = SOCKET_IS_DISCONNECTED;
76 | handler.sendMessage(msg);
77 | }
78 |
79 | @Override
80 | public void run() {
81 | socket = null;
82 |
83 | try {
84 | boolean serverStarted = false;
85 |
86 | publishConnecting();
87 |
88 | try {
89 | InetAddress serverAddr = InetAddress.getByAddress(getIpAddress());
90 | socket = new Socket(serverAddr, getPort());
91 | socket.setReuseAddress(true);
92 |
93 | out = socket.getOutputStream();
94 | in = socket.getInputStream();
95 |
96 | if (out == null || in == null) {
97 | socket.close();
98 | } else {
99 | serverStarted = true;
100 | }
101 | } catch (Exception e) {
102 | LFXLog.d(TAG, "TCPReceiveTask() - TCP Connection Failed.");
103 | }
104 |
105 | if (serverStarted) {
106 | setServerRunning(true);
107 | publishConnected();
108 | } else {
109 | setServerRunning(false);
110 | }
111 |
112 | byte[] buffer = new byte[200];
113 |
114 | while (getServerRunning()) {
115 | int length = in.read(buffer);
116 |
117 | if (length > 0) {
118 | byte[] messageData = new byte[length];
119 | for (int i = 0; i < length; i++) {
120 | messageData[i] = buffer[i];
121 | }
122 |
123 | byte[] ipAddress = socket.getInetAddress().getAddress();
124 | SocketMessage message = new SocketMessage(messageData, ipAddress, length);
125 |
126 | SocketMessage[] messages = new SocketMessage[]{message};
127 | publishProgress((SocketMessage[]) messages);
128 | } else if (length < 0) {
129 | LFXLog.d(TAG, "TCPReceiveTask() - TCP Socket has been closed.");
130 | close();
131 | }
132 | }
133 | } catch (Exception e) {
134 | e.printStackTrace();
135 | }
136 |
137 | close();
138 |
139 | publishDisconnected();
140 |
141 | LFXLog.d(TAG, "TCPReceiveTask() - TCP Socket Monitor Ended Execution.");
142 | }
143 | }
144 |
145 | @Override
146 | public void connect(byte[] ipAddress, int port) {
147 | bind(ipAddress, port);
148 |
149 | state = SocketState.CONNECTING;
150 |
151 | asyncSocket = new Thread(new TCPReceiveTask(handler), "TCPReceiveTask");
152 | asyncSocket.start();
153 | }
154 |
155 | private void closeInputStream() {
156 | if (in != null) {
157 | try {
158 | in.close();
159 | } catch (Exception e) {
160 | e.printStackTrace();
161 | }
162 | }
163 | }
164 |
165 | private void closeOutputStream() {
166 | if (out != null) {
167 | try {
168 | out.close();
169 | } catch (Exception e) {
170 | e.printStackTrace();
171 | }
172 | }
173 | }
174 |
175 | private void closeSocket() {
176 | try {
177 | if (socket != null) {
178 | socket.close();
179 | }
180 | } catch (IOException e) {
181 | e.printStackTrace();
182 | }
183 | }
184 |
185 | @Override
186 | public void close() {
187 | super.close();
188 | closeInputStream();
189 | closeOutputStream();
190 | closeSocket();
191 | }
192 |
193 | public class SendMessageTask implements Runnable {
194 | private SocketMessage[] messages;
195 |
196 | public SendMessageTask(SocketMessage... messages) {
197 | this.messages = messages;
198 | }
199 |
200 | @Override
201 | public void run() {
202 | for (SocketMessage message : messages) {
203 | try {
204 | byte[] messageData = message.getMessageData();
205 |
206 | if (out != null) {
207 | DataOutputStream dos = new DataOutputStream(out);
208 |
209 | if (messageData.length > 0) {
210 | dos.write(messageData, 0, messageData.length);
211 | }
212 |
213 | dos.flush();
214 | }
215 |
216 | //LFXLog.d(TAG, "Message Sent Via TCP: " + MessageUnPacker.getMessageType( messageData).toString());
217 | } catch (Exception e) {
218 | e.printStackTrace();
219 | close();
220 | }
221 | }
222 | }
223 | }
224 |
225 | public void sendMessages(SocketMessage[] messages) {
226 | asyncSocketOutTask = new Thread(new SendMessageTask(messages));
227 | asyncSocketOutTask.start();
228 | }
229 |
230 | @Override
231 | public ConnectionType getConnectionType() {
232 | return ConnectionType.TCP;
233 | }
234 | }
235 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/internal/LFXBinaryTargetID.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXBinaryTargetID.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.entities.internal;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.util.LFXByteUtils;
14 |
15 | public class LFXBinaryTargetID {
16 | // Canonical representation is a string
17 | //
18 | // Device: 6 byte, 12 char hex string (704192abcd12)
19 | // Group: uint64 bitfield prefixed with # in hex (#8 - group 4)
20 | // Broadcast: "*"
21 |
22 | private static final int DEVICE_TARGET_ID_BYTES = 6;
23 | private static final int TAG_TARGET_ID_BYTES = 8;
24 | private static final int TAG_TARGET_ID_BITS = TAG_TARGET_ID_BYTES * 8;
25 |
26 | public enum LFXBinaryTargetType {
27 | DEVICE,
28 | TAG,
29 | BROADCAST, // Special case of a group
30 | }
31 |
32 | public static class TagField {
33 | public byte[] tagData;
34 |
35 | public TagField() {
36 | tagData = new byte[8];
37 | }
38 |
39 | public boolean equals(TagField otherTagField) {
40 | if (otherTagField == null) {
41 | return false;
42 | }
43 |
44 | if (LFXByteUtils.areByteArraysEqual(tagData, otherTagField.tagData)) {
45 | return true;
46 | }
47 |
48 | return false;
49 | }
50 | }
51 |
52 | private LFXBinaryTargetType targetType;
53 | private TagField groupTagField = new TagField();
54 | byte[] deviceBytes;
55 |
56 | public LFXBinaryTargetType getTargetType() {
57 | return targetType;
58 | }
59 |
60 | public static LFXBinaryTargetID getTargetIDWithString(String stringValue) {
61 | if (stringValue.contains("*")) {
62 | return getBroadcastTargetID();
63 | }
64 |
65 | if (stringValue.contains("#")) {
66 | String hexString = stringValue.substring(stringValue.indexOf('#') + 1);
67 | TagField tagField = new TagField();
68 | tagField.tagData = LFXByteUtils.hexStringToByteArray(hexString);
69 | return getGroupTargetIDWithTagField(tagField);
70 | } else {
71 | // Device Target (6 bytes)
72 | return getDeviceTargetIDWithString(stringValue);
73 | }
74 | }
75 |
76 | // Device Targets
77 | public static LFXBinaryTargetID getDeviceTargetIDWithData(byte[] data) {
78 | LFXBinaryTargetID targetID = new LFXBinaryTargetID();
79 | targetID.targetType = LFXBinaryTargetType.DEVICE;
80 | targetID.deviceBytes = new byte[DEVICE_TARGET_ID_BYTES];
81 | LFXByteUtils.copyBytesIntoByteArrayUpToLength(targetID.deviceBytes, data, DEVICE_TARGET_ID_BYTES);
82 | return targetID;
83 | }
84 |
85 | public static LFXBinaryTargetID getDeviceTargetIDWithString(String string) {
86 | byte[] data = LFXByteUtils.hexStringToByteArray(string);
87 | return getDeviceTargetIDWithData(data);
88 | }
89 |
90 | public byte[] getDeviceDataValue() {
91 | return deviceBytes;
92 | }
93 |
94 | // Group Targets
95 | public static LFXBinaryTargetID getGroupTargetIDWithTagField(TagField tagField) {
96 | LFXBinaryTargetID targetID = new LFXBinaryTargetID();
97 | targetID.targetType = LFXByteUtils.isByteArrayEmpty(tagField.tagData) ? LFXBinaryTargetType.BROADCAST : LFXBinaryTargetType.TAG;
98 | targetID.groupTagField = tagField;
99 | return targetID;
100 | }
101 |
102 | // Broadcast Targets
103 | public static LFXBinaryTargetID getBroadcastTargetID() {
104 | LFXBinaryTargetID targetID = new LFXBinaryTargetID();
105 | targetID.targetType = LFXBinaryTargetType.BROADCAST;
106 | return targetID;
107 | }
108 |
109 | public static ArrayList enumerateTagField(TagField tagField) {
110 | ArrayList singularTagFields = new ArrayList();
111 |
112 | for (int tagIndex = 0; tagIndex < TAG_TARGET_ID_BITS; tagIndex++) {
113 | if (LFXByteUtils.isBitSet(tagField.tagData, tagIndex)) {
114 | TagField tempTagField = new TagField();
115 | byte[] tempTagBytes = new byte[TAG_TARGET_ID_BYTES];
116 | LFXByteUtils.setBit(tempTagBytes, tagIndex);
117 | tempTagField.tagData = tempTagBytes;
118 |
119 | singularTagFields.add(tempTagField);
120 | }
121 | }
122 |
123 | return singularTagFields;
124 | }
125 |
126 | public String getStringValue() {
127 | switch (targetType) {
128 | case BROADCAST: {
129 | return "*";
130 | }
131 | case TAG: {
132 | return "#" + LFXByteUtils.byteArrayToHexString(groupTagField.tagData);
133 | }
134 | case DEVICE: {
135 | return LFXByteUtils.byteArrayToHexString(deviceBytes); //[_deviceBytes lfx_hexStringValue];
136 | }
137 | }
138 |
139 | return "LFXBinaryTarget: Unknown Type";
140 | }
141 |
142 | public String toString() {
143 | return "";
144 | }
145 |
146 | public LFXBinaryTargetType geTargetType() {
147 | return targetType;
148 | }
149 |
150 | public TagField getGroupTagField() {
151 | return groupTagField;
152 | }
153 |
154 | public ArrayList getIndividualGroupTargetIDs() {
155 | // For future optimisation, this could get generated once, when a groupTargetID is created
156 | ArrayList targetIDs = new ArrayList();
157 |
158 | for (int bit = 0; bit < TAG_TARGET_ID_BITS; bit++) {
159 | if (LFXByteUtils.isBitSet(groupTagField.tagData, bit)) {
160 | byte[] newTag = new byte[TAG_TARGET_ID_BYTES];
161 | LFXByteUtils.setBit(newTag, bit);
162 | TagField tagField = new TagField();
163 | tagField.tagData = newTag;
164 | targetIDs.add(getGroupTargetIDWithTagField(tagField));
165 | }
166 | }
167 |
168 | return targetIDs;
169 | }
170 |
171 | public String getDebugStringValue() {
172 | if (getTargetType() == LFXBinaryTargetType.DEVICE) {
173 | return LFXByteUtils.byteArrayToHexString(this.deviceBytes);
174 | } else if (getTargetType() == LFXBinaryTargetType.TAG) {
175 | return LFXByteUtils.byteArrayToHexString(this.groupTagField.tagData);
176 | } else {
177 | return LFXByteUtils.byteArrayToHexString(this.groupTagField.tagData);
178 | }
179 | }
180 |
181 | public boolean equal(LFXBinaryTargetID aTargetID) {
182 | if (aTargetID == null) {
183 | return false;
184 | }
185 |
186 | if (targetType != aTargetID.targetType) {
187 | return false;
188 | }
189 |
190 | switch (targetType) {
191 | case BROADCAST:
192 | return true;
193 | case DEVICE:
194 | return LFXByteUtils.areByteArraysEqual(deviceBytes, aTargetID.deviceBytes);//[_deviceBytes isEqualToData:aTargetID->_deviceBytes];
195 | case TAG:
196 | return LFXByteUtils.areByteArraysEqual(groupTagField.tagData, aTargetID.groupTagField.tagData);
197 | }
198 |
199 | return false;
200 | }
201 |
202 | public boolean equals(LFXBinaryTargetID aTargetID) {
203 | if (aTargetID == null) {
204 | return false;
205 | }
206 |
207 | if (!LFXByteUtils.areByteArraysEqual(deviceBytes, aTargetID.deviceBytes)) {
208 | return false;
209 | }
210 |
211 | return true;
212 | }
213 | }
214 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/transport_manager/lan/gateway_discovery/LFXGatewayDiscoveryController.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXGatewayDiscoveryController.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.transport_manager.lan.gateway_discovery;
10 |
11 | import java.util.ArrayList;
12 | import java.util.Timer;
13 | import java.util.TimerTask;
14 |
15 | import lifx.java.android.entities.internal.LFXBinaryPath;
16 | import lifx.java.android.entities.internal.LFXGatewayDescriptor;
17 | import lifx.java.android.entities.internal.LFXMessage;
18 | import lifx.java.android.entities.internal.LFXMessageObservationDescriptor.LFXMessageObserverCallback;
19 | import lifx.java.android.entities.internal.structle.LxProtocolDevice;
20 | import lifx.java.android.entities.internal.structle.LxProtocol.Type;
21 | import lifx.java.android.entities.internal.structle.LxProtocolDevice.Service;
22 | import lifx.java.android.network_context.internal.transport_manager.lan.LFXLANTransportManager;
23 | import lifx.java.android.util.LFXLog;
24 | import lifx.java.android.util.LFXTimerUtils;
25 |
26 | public class LFXGatewayDiscoveryController {
27 | private final static String TAG = LFXGatewayDiscoveryController.class.getSimpleName();
28 |
29 | public enum LFXGatewayDiscoveryMode {
30 | NORMAL, // 30 seconds
31 | ACTIVELY_SEARCHING, // 1 second
32 | }
33 |
34 | ;
35 |
36 | private LFXGatewayDiscoveryControllerListener listener;
37 | private boolean ended = false;
38 | private Timer discoveryTimer;
39 | private LFXLANTransportManager transportManager;
40 | private ArrayList table;
41 |
42 | // This property will change how often DeviceGetPanGateway messages are broadcast
43 | private LFXGatewayDiscoveryMode discoveryMode;
44 |
45 | public static LFXGatewayDiscoveryController getGatewayDiscoveryControllerWithLANTransportManager(LFXLANTransportManager transportManager, LFXGatewayDiscoveryControllerListener listener) {
46 | LFXLog.d(TAG, "LFXGatewayDiscoveryController() - Static constructor");
47 | LFXGatewayDiscoveryController discoveryTable = new LFXGatewayDiscoveryController();
48 | discoveryTable.table = new ArrayList();
49 | discoveryTable.transportManager = transportManager;
50 | discoveryTable.listener = listener;
51 |
52 | discoveryTable.transportManager.addMessageObserverObjectWithCallback(discoveryTable, new LFXMessageObserverCallback() {
53 | @Override
54 | public void run(Object context, LFXMessage message) {
55 | LFXGatewayDiscoveryController discoveryTable = (LFXGatewayDiscoveryController) context;
56 |
57 | if (message.getType() != Type.LX_PROTOCOL_DEVICE_STATE_PAN_GATEWAY) {
58 | return;
59 | }
60 |
61 | discoveryTable.handleStatePANGatewayMessage(message);
62 | }
63 | });
64 |
65 | discoveryTable.discoveryMode = LFXGatewayDiscoveryMode.NORMAL;
66 | discoveryTable.configureTimerForDiscoveryMode(discoveryTable.discoveryMode);
67 | return discoveryTable;
68 | }
69 |
70 | public interface LFXGatewayDiscoveryControllerListener {
71 | public void gatewayDiscoveryControllerDidUpdateEntry(LFXGatewayDiscoveryController table, LFXGatewayDiscoveryTableEntry tableEntry, boolean entryIsNew);
72 | }
73 |
74 | @SuppressWarnings({"unchecked", "unused"})
75 | private ArrayList getAllGatewayDiscoveryTableEntries() {
76 | return (ArrayList) table.clone();
77 | }
78 |
79 | public void removeAllGatewayDiscoveryTableEntries() {
80 | table.clear();
81 | }
82 |
83 | public void handleStatePANGatewayMessage(LFXMessage statePanGateway) {
84 | LxProtocolDevice.StatePanGateway statePanGatewayPayload = (LxProtocolDevice.StatePanGateway) statePanGateway.getPayload();
85 |
86 | String host = statePanGateway.getSourceNetworkHost();
87 | int port = (int) statePanGatewayPayload.getPort().getValue();
88 | LFXBinaryPath path = statePanGateway.getPath();
89 | Service service = LxProtocolDevice.serviceMap.get(statePanGatewayPayload.getService().getValue());
90 |
91 | // TODO: remove to enable TCP
92 | if (service == Service.LX_PROTOCOL_DEVICE_SERVICE_TCP) {
93 | LFXLog.e(TAG, "handleStatePANGatewayMessage() - TCP Protocol unsupported");
94 | return;
95 | }
96 | else {
97 | LFXLog.i(TAG, "handleStatePANGatewayMessage() - " + service.toString());
98 | }
99 |
100 | LFXGatewayDescriptor gatewayDescriptor = LFXGatewayDescriptor.getGatewayDescriptorWithHostPortPathService(host, port, path, service);
101 |
102 | LFXGatewayDiscoveryTableEntry tableEntry = null;
103 |
104 | for (LFXGatewayDiscoveryTableEntry anEntry : table) {
105 | if (anEntry.getGatewayDescriptor().equals(gatewayDescriptor)) {
106 | tableEntry = anEntry;
107 | break;
108 | }
109 | }
110 |
111 | if (tableEntry != null) {
112 | tableEntry.setLastDiscoveryResponseDate(statePanGateway.getTimestamp());
113 | listener.gatewayDiscoveryControllerDidUpdateEntry(this, tableEntry, false);
114 | } else {
115 | tableEntry = new LFXGatewayDiscoveryTableEntry();
116 | tableEntry.setGatewayDescriptor(gatewayDescriptor);
117 | tableEntry.setLastDiscoveryResponseDate(statePanGateway.getTimestamp());
118 | table.add(tableEntry);
119 | listener.gatewayDiscoveryControllerDidUpdateEntry(this, tableEntry, true);
120 | }
121 | }
122 |
123 | public void sendGatewayDiscoveryMessage() {
124 | LFXMessage getPANGateway = LFXMessage.messageWithType(Type.LX_PROTOCOL_DEVICE_GET_PAN_GATEWAY);
125 | transportManager.sendBroadcastUDPMessage(getPANGateway);
126 | }
127 |
128 | public void setDiscoveryMode(LFXGatewayDiscoveryMode discoveryMode) {
129 | if (this.discoveryMode == discoveryMode) {
130 | return;
131 | }
132 | this.discoveryMode = discoveryMode;
133 | configureTimerForDiscoveryMode(discoveryMode);
134 | }
135 |
136 | private Runnable getDiscoverTimerTask() {
137 | Runnable discoverTimerTask = new TimerTask() {
138 | public void run() {
139 | discoveryTimerDidFire();
140 | }
141 | };
142 |
143 | return discoverTimerTask;
144 | }
145 |
146 | public void configureTimerForDiscoveryMode(LFXGatewayDiscoveryMode discoveryMode) {
147 | long duration = 1000;
148 | switch (discoveryMode) {
149 | case NORMAL:
150 | duration = 30000;
151 | break;
152 | case ACTIVELY_SEARCHING:
153 | duration = 1000;
154 | break;
155 | }
156 |
157 | if (discoveryTimer != null) {
158 | discoveryTimer.cancel();
159 | discoveryTimer.purge();
160 | }
161 |
162 | LFXLog.d(TAG, "configureTimerForDiscoveryMode() - Mode="+discoveryMode+" Timer Period: " + duration);
163 | discoveryTimer = LFXTimerUtils.getTimerTaskWithPeriod(getDiscoverTimerTask(), duration, false, "DisoveryTimer");
164 | }
165 |
166 | public void discoveryTimerDidFire() {
167 | if (!ended) {
168 | sendGatewayDiscoveryMessage();
169 | }
170 | }
171 |
172 | public void shutDown() {
173 | if (discoveryTimer != null) {
174 | discoveryTimer.cancel();
175 | discoveryTimer.purge();
176 | discoveryTimer=null;
177 | }
178 | ended = true;
179 | }
180 | }
181 |
182 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/transport_manager/gateway_connection/LFXSocketGeneric.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSocketGeneric.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.transport_manager.gateway_connection;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.entities.internal.LFXMessage;
14 | import lifx.java.android.util.LFXByteUtils;
15 |
16 | import android.content.Context;
17 | import android.net.DhcpInfo;
18 | import android.net.wifi.WifiManager;
19 | import android.os.Handler;
20 | import android.os.Looper;
21 | import android.os.Message;
22 |
23 | public abstract class LFXSocketGeneric {
24 | protected static final int SOCKET_RECEIVED_MESSAGE = 4;
25 | protected static final int SOCKET_IS_CONNECTING = 5;
26 | protected static final int SOCKET_IS_CONNECTED = 6;
27 | protected static final int SOCKET_IS_DISCONNECTED = 7;
28 |
29 | public enum SocketState {
30 | CONNECTING,
31 | CONNECTED,
32 | DISCONNECTED
33 | }
34 |
35 | public enum ConnectionType {
36 | UDP,
37 | TCP
38 | }
39 |
40 | public abstract void connect(byte[] ipAddress, int port);
41 |
42 | public abstract void sendMessages(SocketMessage[] messages);
43 |
44 | public abstract ConnectionType getConnectionType();
45 |
46 | public static class SocketMessage {
47 | private byte[] message;
48 | private byte[] ipAddress;
49 | private int port;
50 |
51 | public SocketMessage(byte[] message) {
52 | this(message, null, 0);
53 | }
54 |
55 | public SocketMessage(byte[] message, byte[] ipAddress, int port) {
56 | int size = LFXMessage.getSizeFromMessageData(message);
57 | byte[] bytes = new byte[size];
58 | LFXByteUtils.copyBytesIntoByteArrayUpToLength(bytes, message, size);
59 | this.message = bytes;
60 | this.ipAddress = ipAddress;
61 | this.port = port;
62 | }
63 |
64 | public byte[] getMessageData() {
65 | return message;
66 | }
67 |
68 | public byte[] getIpAddress() {
69 | return ipAddress;
70 | }
71 |
72 | public int getPort() {
73 | return port;
74 | }
75 |
76 | public SocketMessage cloneWithIpAddressAndPort(byte[] ipAddress, int port) {
77 | byte[] cloneMessage = new byte[message.length];
78 | for (int i = 0; i < message.length; i++) {
79 | cloneMessage[i] = message[i];
80 | }
81 |
82 | byte[] cloneIpAddress = new byte[ipAddress.length];
83 | for (int i = 0; i < ipAddress.length; i++) {
84 | cloneIpAddress[i] = ipAddress[i];
85 | }
86 |
87 | SocketMessage clone = new SocketMessage(cloneMessage, cloneIpAddress, port);
88 |
89 | return clone;
90 | }
91 | }
92 |
93 | public interface SocketStateListener {
94 | public void notifySocketStateChanged(LFXSocketGeneric socket, SocketState state);
95 | }
96 |
97 | public interface SocketMessageListener {
98 | public void notifyMessageReceived(SocketMessage message);
99 | }
100 |
101 | private ArrayList stateListeners;
102 | private ArrayList listeners;
103 | private boolean serverRunning = true;
104 | private byte[] ipAddress;
105 | private int port;
106 | protected Handler handler;
107 | protected SocketState state = SocketState.DISCONNECTED;
108 | protected Object closeLock = new Object();
109 |
110 | public LFXSocketGeneric() {
111 | stateListeners = new ArrayList();
112 | listeners = new ArrayList();
113 | setHandler();
114 | }
115 |
116 | // public LFXSocketGeneric( byte[] ipAddress, int port)
117 | // {
118 | // this();
119 | // this.ipAddress = ipAddress;
120 | // this.port = port;
121 | // }
122 |
123 | protected void bind(byte[] ipAddress, int port) {
124 | this.ipAddress = ipAddress;
125 | this.port = port;
126 | }
127 |
128 | public Handler getMessageHandler() {
129 | return handler;
130 | }
131 |
132 | public SocketState getSocketState() {
133 | return state;
134 | }
135 |
136 | protected byte[] getIpAddress() {
137 | return ipAddress;
138 | }
139 |
140 | private void setHandler() {
141 | handler = new Handler(Looper.getMainLooper()) {
142 | @Override
143 | public void handleMessage(Message message) {
144 | int type = message.what;
145 |
146 | if (type == SOCKET_RECEIVED_MESSAGE) {
147 | notifyAllListenersMessageReceived((SocketMessage) message.obj);
148 | } else if (type == SOCKET_IS_CONNECTING) {
149 | state = SocketState.CONNECTING;
150 | notifyAllListenersSocketStateChanged(SocketState.CONNECTING);
151 | } else if (type == SOCKET_IS_CONNECTED) {
152 | state = SocketState.CONNECTED;
153 | notifyAllListenersSocketStateChanged(SocketState.CONNECTED);
154 | } else if (type == SOCKET_IS_DISCONNECTED) {
155 | state = SocketState.DISCONNECTED;
156 | notifyAllListenersSocketStateChanged(SocketState.DISCONNECTED);
157 | }
158 | }
159 | };
160 | }
161 |
162 | protected int getPort() {
163 | return port;
164 | }
165 |
166 | public final void addStateListener(SocketStateListener listener) {
167 | if (!stateListeners.contains(listener)) {
168 | stateListeners.add(listener);
169 | }
170 | }
171 |
172 | public final void removeConnectListener(SocketStateListener listener) {
173 | if (stateListeners.contains(listener)) {
174 | stateListeners.remove(listener);
175 | }
176 | }
177 |
178 | protected void notifyAllListenersSocketStateChanged(SocketState state) {
179 | for (SocketStateListener listener : stateListeners) {
180 | listener.notifySocketStateChanged(this, state);
181 | }
182 | }
183 |
184 | public final void addMessageListener(SocketMessageListener listener) {
185 | if (!listeners.contains(listener)) {
186 | listeners.add(listener);
187 | }
188 | }
189 |
190 | public final void removeMessageListener(SocketMessageListener listener) {
191 | if (listeners.contains(listener)) {
192 | listeners.remove(listener);
193 | }
194 | }
195 |
196 | protected void notifyAllListenersMessageReceived(SocketMessage message) {
197 | for (SocketMessageListener listener : listeners) {
198 | listener.notifyMessageReceived(message);
199 | }
200 | }
201 |
202 | public final void sendMessage(SocketMessage message) {
203 | SocketMessage[] messages = new SocketMessage[]{message};
204 | sendMessages(messages);
205 | }
206 |
207 | public void close() {
208 | setServerRunning(false);
209 | }
210 |
211 | protected void setServerRunning(boolean serverRunning) {
212 | synchronized (closeLock) {
213 | this.serverRunning = serverRunning;
214 | }
215 | }
216 |
217 | protected boolean getServerRunning() {
218 | boolean value = false;
219 |
220 | synchronized (closeLock) {
221 | value = serverRunning;
222 | }
223 |
224 | return value;
225 | }
226 |
227 | public final static byte[] getBroadcastAddress(Context context) {
228 | WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
229 | DhcpInfo dhcp = wifi.getDhcpInfo();
230 | // handle null somehow
231 |
232 | int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
233 | byte[] quads = new byte[4];
234 |
235 | for (int k = 0; k < 4; k++) {
236 | quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
237 | }
238 |
239 | return quads;
240 | }
241 | }
242 |
--------------------------------------------------------------------------------
/examples/src/com/example/lifx_sdk_samples/LFXSDKLightEditLabelActivity.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXSDKLightEditLabelActivity.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package com.example.lifx_sdk_samples;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.client.LFXClient;
14 | import lifx.java.android.entities.LFXHSBKColor;
15 | import lifx.java.android.entities.LFXTypes.LFXFuzzyPowerState;
16 | import lifx.java.android.entities.LFXTypes.LFXPowerState;
17 | import lifx.java.android.light.LFXLight;
18 | import lifx.java.android.light.LFXLight.LFXLightListener;
19 | import lifx.java.android.light.LFXLightCollection;
20 | import lifx.java.android.light.LFXLightCollection.LFXLightCollectionListener;
21 | import lifx.java.android.light.LFXTaggedLightCollection;
22 | import lifx.java.android.network_context.LFXNetworkContext;
23 | import lifx.java.android.network_context.LFXNetworkContext.LFXNetworkContextListener;
24 | import android.os.Bundle;
25 | import android.app.Activity;
26 | import android.app.AlertDialog;
27 | import android.content.DialogInterface;
28 | import android.view.Menu;
29 | import android.view.View;
30 | import android.widget.AdapterView;
31 | import android.widget.AdapterView.OnItemClickListener;
32 | import android.widget.EditText;
33 | import android.widget.ListView;
34 | import android.widget.Toast;
35 |
36 | public class LFXSDKLightEditLabelActivity extends Activity implements LFXLightListener, LFXLightCollectionListener, LFXNetworkContextListener
37 | {
38 | private LFXNetworkContext networkContext;
39 | private LFXSDKLightListAdapter lightListAdapter;
40 | private LFXSDKTaggedLightCollectionListAdapter groupListAdapter;
41 |
42 | @Override
43 | protected void onCreate( Bundle savedInstanceState)
44 | {
45 | super.onCreate( savedInstanceState);
46 | setContentView( R.layout.lifx_list_sample_layout);
47 |
48 | networkContext = LFXClient.getSharedInstance( getApplicationContext()).getLocalNetworkContext();
49 | networkContext.addNetworkContextListener( this);
50 | networkContext.getAllLightsCollection().addLightCollectionListener( this);
51 |
52 | ListView lightListView = (ListView) findViewById( R.id.light_list_view);
53 | lightListAdapter = new LFXSDKLightListAdapter( this);
54 | lightListView.setAdapter( lightListAdapter);
55 |
56 | ListView groupListView = (ListView) findViewById( R.id.group_list_view);
57 | groupListAdapter = new LFXSDKTaggedLightCollectionListAdapter( this);
58 | groupListView.setAdapter( groupListAdapter);
59 |
60 | updateStateFromLIFX();
61 |
62 | lightListView.setOnItemClickListener( new OnItemClickListener()
63 | {
64 | @Override
65 | public void onItemClick( AdapterView> arg0, View arg1, int position, long arg3)
66 | {
67 | LFXLight light = (LFXLight) lightListAdapter.getItem( position);
68 | showLabelDialogForLight( light);
69 | }
70 | });
71 |
72 | groupListView.setOnItemClickListener( new OnItemClickListener()
73 | {
74 | @Override
75 | public void onItemClick( AdapterView> arg0, View arg1, int position, long arg3)
76 | {
77 | LFXTaggedLightCollection lightCollection = (LFXTaggedLightCollection) groupListAdapter.getItem( position);
78 | showLabelDialogForLightCollection( lightCollection);
79 | }
80 | });
81 | }
82 |
83 | public void showLabelDialogForLight( LFXLight light)
84 | {
85 | final LFXLight finalLight = light;
86 |
87 | AlertDialog.Builder alert = new AlertDialog.Builder( this);
88 | alert.setTitle("Rename Light Too:");
89 |
90 | // Set an EditText view to get user input
91 | final EditText input = new EditText( this);
92 | alert.setView(input);
93 |
94 | alert.setPositiveButton( "Ok", new DialogInterface.OnClickListener()
95 | {
96 | public void onClick( DialogInterface dialog, int whichButton)
97 | {
98 | String value = input.getText().toString();
99 | finalLight.setLabel( value);
100 | return;
101 | }
102 | });
103 |
104 | alert.setNegativeButton( "Cancel", new DialogInterface.OnClickListener()
105 | {
106 | public void onClick(DialogInterface dialog, int which)
107 | {
108 | return;
109 | }
110 | });
111 |
112 | alert.show();
113 | }
114 |
115 | public void showLabelDialogForLightCollection( LFXTaggedLightCollection lightCollection)
116 | {
117 | final LFXTaggedLightCollection finalLightCollection = lightCollection;
118 |
119 | AlertDialog.Builder alert = new AlertDialog.Builder( this);
120 | alert.setTitle("Rename Group Too:");
121 |
122 | // Set an EditText view to get user input
123 | final EditText input = new EditText( this);
124 | alert.setView(input);
125 |
126 | alert.setPositiveButton( "Ok", new DialogInterface.OnClickListener()
127 | {
128 | public void onClick( DialogInterface dialog, int whichButton)
129 | {
130 | String value = input.getText().toString();
131 | finalLightCollection.setLabel( value);
132 | return;
133 | }
134 | });
135 |
136 | alert.setNegativeButton( "Cancel", new DialogInterface.OnClickListener()
137 | {
138 | public void onClick(DialogInterface dialog, int which)
139 | {
140 | return;
141 | }
142 | });
143 |
144 | alert.show();
145 | }
146 |
147 | @Override
148 | public boolean onCreateOptionsMenu( Menu menu)
149 | {
150 | getMenuInflater().inflate( R.menu.sample, menu);
151 | return true;
152 | }
153 |
154 | @Override
155 | protected void onPause()
156 | {
157 | networkContext.removeNetworkContextListener( this);
158 | super.onPause();
159 | }
160 |
161 | private void updateStateFromLIFX()
162 | {
163 | ArrayList allLights = networkContext.getAllLightsCollection().getLights();
164 | lightListAdapter.updateWithLights( allLights);
165 |
166 | ArrayList lightCollections = networkContext.getTaggedLightCollections();
167 | groupListAdapter.updateWithLightCollections( lightCollections);
168 | }
169 |
170 | @Override
171 | public void networkContextDidConnect( LFXNetworkContext networkContext)
172 | {
173 | Toast toast = Toast.makeText( this, "CONNECTED", Toast.LENGTH_SHORT);
174 | toast.show();
175 | }
176 |
177 | @Override
178 | public void networkContextDidDisconnect( LFXNetworkContext networkContext)
179 | {
180 | Toast toast = Toast.makeText( this, "DISCONNECTED", Toast.LENGTH_SHORT);
181 | toast.show();
182 | }
183 |
184 | @Override
185 | public void networkContextDidAddTaggedLightCollection( LFXNetworkContext networkContext, LFXTaggedLightCollection collection)
186 | {
187 | updateStateFromLIFX();
188 | }
189 |
190 | @Override
191 | public void networkContextDidRemoveTaggedLightCollection( LFXNetworkContext networkContext, LFXTaggedLightCollection collection)
192 | {
193 | updateStateFromLIFX();
194 | }
195 |
196 | @Override
197 | public void lightCollectionDidAddLight( LFXLightCollection lightCollection, LFXLight light)
198 | {
199 | updateStateFromLIFX();
200 | light.addLightListener( this);
201 | }
202 |
203 | @Override
204 | public void lightCollectionDidRemoveLight( LFXLightCollection lightCollection, LFXLight light)
205 | {
206 | updateStateFromLIFX();
207 | light.removeLightListener( this);
208 | }
209 |
210 | @Override
211 | public void lightCollectionDidChangeLabel( LFXLightCollection lightCollection, String label) {}
212 |
213 | @Override
214 | public void lightCollectionDidChangeColor( LFXLightCollection lightCollection, LFXHSBKColor color) {}
215 |
216 | @Override
217 | public void lightCollectionDidChangeFuzzyPowerState( LFXLightCollection lightCollection, LFXFuzzyPowerState fuzzyPowerState) {}
218 |
219 | @Override
220 | public void lightDidChangeLabel( LFXLight light, String label)
221 | {
222 | updateStateFromLIFX();
223 | }
224 |
225 | @Override
226 | public void lightDidChangeColor( LFXLight light, LFXHSBKColor color)
227 | {
228 | updateStateFromLIFX();
229 | }
230 |
231 | @Override
232 | public void lightDidChangePowerState( LFXLight light, LFXPowerState powerState)
233 | {
234 | updateStateFromLIFX();
235 | }
236 | }
237 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/entities/internal/structle/LxProtocolSensor.java:
--------------------------------------------------------------------------------
1 | //
2 | // LxProtocolSensor.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | // Start File: @./LxProtocolSensor.java
10 |
11 | package lifx.java.android.entities.internal.structle;
12 |
13 | /*
14 | **** GENERATED CODE ****
15 | Start Of File: LxProtocolSensor.java
16 | */
17 |
18 | import java.util.HashMap;
19 |
20 | import android.annotation.SuppressLint;
21 |
22 | import lifx.java.android.entities.internal.structle.StructleTypes.Bool8;
23 | import lifx.java.android.entities.internal.structle.StructleTypes.Float32;
24 | import lifx.java.android.entities.internal.structle.StructleTypes.Int16;
25 | import lifx.java.android.entities.internal.structle.StructleTypes.Int32;
26 | import lifx.java.android.entities.internal.structle.StructleTypes.Int64;
27 | import lifx.java.android.entities.internal.structle.StructleTypes.LxProtocolTypeBase;
28 | import lifx.java.android.entities.internal.structle.StructleTypes.ProtocolField;
29 | import lifx.java.android.entities.internal.structle.StructleTypes.RoutingField;
30 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt16;
31 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt32;
32 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt64;
33 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt8;
34 |
35 | @SuppressLint("UseSparseArrays")
36 | @SuppressWarnings("unused")
37 | public class LxProtocolSensor {
38 |
39 |
40 | public static class GetAmbientLight extends LxProtocolTypeBase // Struct: Lx::Protocol::Sensor::GetAmbientLight
41 | {
42 |
43 | private static final int PAYLOAD_SIZE = 0;
44 |
45 | public GetAmbientLight(byte[] bytes) {
46 | this(bytes, 0);
47 | }
48 |
49 | public GetAmbientLight(byte[] bytes, int initialOffset) {
50 | }
51 |
52 | public GetAmbientLight(Object padding
53 | ) {
54 | }
55 |
56 |
57 | public void printMessageData() {
58 | }
59 |
60 | public static void loadMessageDataWithPayloadAtOffset(byte[] messageData, int offset) {
61 | byte[] memberData; // = name.getBytes();
62 |
63 | }
64 |
65 | public static void loadMessageDataWithPayloadAtDefaultOffset(byte[] messageData) {
66 | int offset = PAYLOAD_OFFSET;
67 |
68 | loadMessageDataWithPayloadAtOffset(messageData, offset
69 | );
70 | }
71 |
72 | public byte[] getBytes() {
73 | int offset = 0;
74 |
75 | byte[] bytes = new byte[getPayloadSize()];
76 |
77 | byte[] memberData;
78 |
79 |
80 | return bytes;
81 | }
82 |
83 | public static int getPayloadSize() {
84 | return PAYLOAD_SIZE;
85 | }
86 | }
87 |
88 | public static class StateAmbientLight extends LxProtocolTypeBase // Struct: Lx::Protocol::Sensor::StateAmbientLight
89 | {
90 | // Fields: lux;
91 | private Float32 lux; // Field: lux - Structle::Float byte offset: 0
92 |
93 | private static final int PAYLOAD_SIZE = 4;
94 |
95 | public StateAmbientLight(byte[] bytes) {
96 | this(bytes, 0);
97 | }
98 |
99 | public StateAmbientLight(byte[] bytes, int initialOffset) {
100 | byte[] member0Data = new byte[4];
101 | member0Data[0] = bytes[initialOffset + 0];
102 | member0Data[1] = bytes[initialOffset + 1];
103 | member0Data[2] = bytes[initialOffset + 2];
104 | member0Data[3] = bytes[initialOffset + 3];
105 |
106 |
107 | lux = new Float32(member0Data);
108 |
109 | }
110 |
111 | public StateAmbientLight(Object padding
112 | , Float32 lux
113 | ) {
114 | this.lux = lux;
115 | }
116 |
117 | public Float32 getLux() {
118 | return lux;
119 | }
120 |
121 | public void printMessageData() {
122 | lux.printValue("lux"); // Field: lux - Structle::Float byte offset: 4
123 | }
124 |
125 | public static void loadMessageDataWithPayloadAtOffset(byte[] messageData, int offset, Float32 lux) {
126 | byte[] memberData; // = name.getBytes();
127 |
128 |
129 | memberData = lux.getBytes();
130 |
131 | for (int i = 0; i < (memberData.length); i++) {
132 | messageData[(offset + i)] = memberData[i];
133 | }
134 |
135 | offset += memberData.length;
136 | }
137 |
138 | public static void loadMessageDataWithPayloadAtDefaultOffset(byte[] messageData
139 | , Float32 lux
140 | ) {
141 | int offset = PAYLOAD_OFFSET;
142 |
143 | loadMessageDataWithPayloadAtOffset(messageData, offset
144 | , lux
145 | );
146 | }
147 |
148 | public byte[] getBytes() {
149 | int offset = 0;
150 |
151 | byte[] bytes = new byte[getPayloadSize()];
152 |
153 | byte[] memberData;
154 |
155 | // = name.getBytes();
156 | memberData = lux.getBytes();
157 |
158 | for (int i = 0; i < (memberData.length); i++) {
159 | bytes[(offset + i)] = memberData[i];
160 | }
161 |
162 | offset += memberData.length;
163 |
164 | return bytes;
165 | }
166 |
167 | public static int getPayloadSize() {
168 | return PAYLOAD_SIZE;
169 | }
170 | }
171 |
172 | public static class GetDimmerVoltage extends LxProtocolTypeBase // Struct: Lx::Protocol::Sensor::GetDimmerVoltage
173 | {
174 |
175 | private static final int PAYLOAD_SIZE = 0;
176 |
177 | public GetDimmerVoltage(byte[] bytes) {
178 | this(bytes, 0);
179 | }
180 |
181 | public GetDimmerVoltage(byte[] bytes, int initialOffset) {
182 | }
183 |
184 | public GetDimmerVoltage(Object padding
185 | ) {
186 | }
187 |
188 |
189 | public void printMessageData() {
190 | }
191 |
192 | public static void loadMessageDataWithPayloadAtOffset(byte[] messageData, int offset
193 | ) {
194 | byte[] memberData; // = name.getBytes();
195 |
196 | }
197 |
198 | public static void loadMessageDataWithPayloadAtDefaultOffset(byte[] messageData
199 | ) {
200 | int offset = PAYLOAD_OFFSET;
201 |
202 | loadMessageDataWithPayloadAtOffset(messageData, offset
203 | );
204 | }
205 |
206 | public byte[] getBytes() {
207 | int offset = 0;
208 |
209 | byte[] bytes = new byte[getPayloadSize()];
210 |
211 | byte[] memberData;
212 |
213 |
214 | return bytes;
215 | }
216 |
217 | public static int getPayloadSize() {
218 | return PAYLOAD_SIZE;
219 | }
220 | }
221 |
222 | public static class StateDimmerVoltage extends LxProtocolTypeBase // Struct: Lx::Protocol::Sensor::StateDimmerVoltage
223 | {
224 | // Fields: voltage;
225 | private UInt32 voltage; // Field: voltage - Structle::Uint32 byte offset: 0
226 |
227 | private static final int PAYLOAD_SIZE = 4;
228 |
229 | public StateDimmerVoltage(byte[] bytes) {
230 | this(bytes, 0);
231 | }
232 |
233 | public StateDimmerVoltage(byte[] bytes, int initialOffset) {
234 | byte[] member0Data = new byte[4];
235 | member0Data[0] = bytes[initialOffset + 0];
236 | member0Data[1] = bytes[initialOffset + 1];
237 | member0Data[2] = bytes[initialOffset + 2];
238 | member0Data[3] = bytes[initialOffset + 3];
239 |
240 |
241 | voltage = new UInt32(member0Data);
242 |
243 | }
244 |
245 | public StateDimmerVoltage(Object padding
246 | , UInt32 voltage
247 | ) {
248 | this.voltage = voltage;
249 | }
250 |
251 | public UInt32 getVoltage() {
252 | return voltage;
253 | }
254 |
255 | public void printMessageData() {
256 | voltage.printValue("voltage"); // Field: voltage - Structle::Uint32 byte offset: 4
257 | }
258 |
259 | public static void loadMessageDataWithPayloadAtOffset(byte[] messageData, int offset
260 | , UInt32 voltage
261 | ) {
262 | byte[] memberData; // = name.getBytes();
263 |
264 |
265 | memberData = voltage.getBytes();
266 |
267 | for (int i = 0; i < (memberData.length); i++) {
268 | messageData[(offset + i)] = memberData[i];
269 | }
270 |
271 | offset += memberData.length;
272 | }
273 |
274 | public static void loadMessageDataWithPayloadAtDefaultOffset(byte[] messageData
275 | , UInt32 voltage
276 | ) {
277 | int offset = PAYLOAD_OFFSET;
278 |
279 | loadMessageDataWithPayloadAtOffset(messageData, offset
280 | , voltage
281 | );
282 | }
283 |
284 | public byte[] getBytes() {
285 | int offset = 0;
286 |
287 | byte[] bytes = new byte[getPayloadSize()];
288 |
289 | byte[] memberData;
290 |
291 | // = name.getBytes();
292 | memberData = voltage.getBytes();
293 |
294 | for (int i = 0; i < (memberData.length); i++) {
295 | bytes[(offset + i)] = memberData[i];
296 | }
297 |
298 | offset += memberData.length;
299 |
300 | return bytes;
301 | }
302 |
303 | public static int getPayloadSize() {
304 | return PAYLOAD_SIZE;
305 | }
306 | }
307 |
308 | }
309 |
310 | /*
311 | End Of File: LxProtocolSensor.java
312 | */
313 |
314 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/light/LFXLight.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXLight.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.light;
10 |
11 | import java.util.ArrayList;
12 |
13 | import lifx.java.android.entities.LFXHSBKColor;
14 | import lifx.java.android.entities.LFXLightTarget;
15 | import lifx.java.android.entities.LFXTypes.LFXDeviceReachability;
16 | import lifx.java.android.entities.LFXTypes.LFXFuzzyPowerState;
17 | import lifx.java.android.entities.LFXTypes.LFXPowerState;
18 | import lifx.java.android.entities.LFXTypes;
19 | import lifx.java.android.entities.internal.LFXBinaryTypes;
20 | import lifx.java.android.entities.internal.LFXMessage;
21 | import lifx.java.android.entities.internal.LFXTarget;
22 | import lifx.java.android.entities.internal.LFXTarget.LFXTargetType;
23 | import lifx.java.android.entities.internal.structle.LxProtocolDevice;
24 | import lifx.java.android.entities.internal.structle.LxProtocolLight;
25 | import lifx.java.android.entities.internal.structle.LxProtocol.Type;
26 | import lifx.java.android.entities.internal.structle.LxProtocolLight.Hsbk;
27 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt16;
28 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt32;
29 | import lifx.java.android.entities.internal.structle.StructleTypes.UInt8;
30 | import lifx.java.android.network_context.LFXNetworkContext;
31 |
32 | public class LFXLight extends LFXLightTarget {
33 | private final static String TAG=LFXLight.class.getSimpleName();
34 |
35 | public interface LFXLightListener {
36 | public void lightDidChangeLabel(LFXLight light, String label);
37 |
38 | public void lightDidChangeColor(LFXLight light, LFXHSBKColor color);
39 |
40 | public void lightDidChangePowerState(LFXLight light, LFXPowerState powerState);
41 | }
42 |
43 | private LFXNetworkContext networkContext;
44 |
45 | private String deviceID;
46 |
47 | private ArrayList tags = new ArrayList();
48 | private ArrayList taggedCollections = new ArrayList();
49 |
50 | //private LFXDeviceReachability reachability;
51 |
52 | private ArrayList listeners = new ArrayList();
53 |
54 | // Light State
55 | private LFXPowerState powerState;
56 |
57 | private long mostRecentMessageTimestamp;
58 |
59 | /**
60 | *
61 | */
62 | public LFXTargetType getTargetType() {
63 | return LFXTargetType.DEVICE;
64 | }
65 |
66 | public LFXPowerState getPowerState() {
67 | if (powerState == null) {
68 | return LFXPowerState.OFF;
69 | }
70 |
71 | return powerState;
72 | }
73 |
74 | public ArrayList getTaggedCollections() {
75 | return taggedCollections;
76 | }
77 |
78 | public String getDeviceID() {
79 | return deviceID;
80 | }
81 |
82 | private long getMostRecentMessageTimestamp() {
83 | return mostRecentMessageTimestamp;
84 | }
85 |
86 | private void setMostRecentMessageTimestamp(long mostRecentMessageTimestamp) {
87 | this.mostRecentMessageTimestamp = mostRecentMessageTimestamp;
88 | }
89 |
90 | public LFXDeviceReachability getReachability() {
91 | if ((System.currentTimeMillis() - getMostRecentMessageTimestamp()) < 35000) {
92 | return LFXDeviceReachability.REACHABLE;
93 | }
94 |
95 | return LFXDeviceReachability.UNREACHABLE;
96 | }
97 |
98 | public LFXFuzzyPowerState getFuzzyPowerState() {
99 | return LFXTypes.getLFXFuzzyPowerStateFromPowerState(getPowerState());
100 | }
101 |
102 | public void setLabel(String label) {
103 | LFXMessage setLabel = LFXMessage.messageWithTypeAndTarget(Type.LX_PROTOCOL_DEVICE_SET_LABEL, getTarget());
104 | LxProtocolDevice.SetLabel payload = new LxProtocolDevice.SetLabel(new Object(), label);
105 | setLabel.setPayload(payload);
106 | networkContext.sendMessage(setLabel);
107 | }
108 |
109 | public void setColor(LFXHSBKColor color) {
110 | setColorOverDuration(color, 250);
111 | }
112 |
113 | public void setColorOverDuration(LFXHSBKColor color, long duration) {
114 | LFXMessage lightSet = LFXMessage.messageWithTypeAndTarget(Type.LX_PROTOCOL_LIGHT_SET, getTarget());
115 | Object padding = new Object();
116 | UInt8 stream = new UInt8(0);
117 | Hsbk protocolColor = LFXBinaryTypes.getLXProtocolLightHsbkFromLFXHSBKColor(color);
118 | UInt32 protocolDuration = new UInt32(duration);
119 | LxProtocolLight.Set payload = new LxProtocolLight.Set(padding, stream, protocolColor, protocolDuration);
120 | lightSet.setPayload(payload);
121 | networkContext.sendMessage(lightSet);
122 | }
123 |
124 | private void notifyListenerLabelDidChange(String label) {
125 | for (LFXLightListener aListener : listeners) {
126 | aListener.lightDidChangeLabel(this, label);
127 | }
128 | }
129 |
130 | private void notifyListenersColorDidChange(LFXHSBKColor color) {
131 | for (LFXLightListener aListener : listeners) {
132 | aListener.lightDidChangeColor(this, color);
133 | }
134 | }
135 |
136 | private void notifyListenersPowerStateDidChange(LFXPowerState powerState) {
137 | for (LFXLightListener aListener : listeners) {
138 | aListener.lightDidChangePowerState(this, powerState);
139 | }
140 | }
141 |
142 | public void setPowerState(LFXPowerState powerState) {
143 | LFXMessage setPower = LFXMessage.messageWithTypeAndTarget(Type.LX_PROTOCOL_DEVICE_SET_POWER, getTarget());
144 | Object padding = new Object();
145 | UInt16 protocolPowerLevel = LFXBinaryTypes.getLFXProtocolPowerLevelFromLFXPowerState(powerState);
146 | LxProtocolDevice.SetPower payload = new LxProtocolDevice.SetPower(padding, protocolPowerLevel);
147 | setPower.setPayload(payload);
148 | networkContext.sendMessage(setPower);
149 | }
150 |
151 | public static LFXLight lightWithDeviceID(String deviceID, LFXNetworkContext networkContext) {
152 | LFXLight light = new LFXLight();
153 | light.deviceID = deviceID;
154 | light.setTarget(LFXTarget.getDeviceTargetWithDeviceID(deviceID));
155 | light.networkContext = networkContext;
156 | return light;
157 | }
158 |
159 | public void handleMessage(LFXMessage message) {
160 | if (message.isAResponseMessage()) {
161 | setMostRecentMessageTimestamp(System.currentTimeMillis());
162 | }
163 |
164 | switch (message.getType()) {
165 | case LX_PROTOCOL_LIGHT_SET: {
166 | LxProtocolLight.Set payload = (LxProtocolLight.Set) message.getPayload();
167 | colorDidChangeTo(LFXBinaryTypes.getLFXHSBKColorFromLXProtocolLightHsbk(payload.getColor()));
168 | break;
169 | }
170 | case LX_PROTOCOL_LIGHT_STATE: {
171 | LxProtocolLight.State payload = (LxProtocolLight.State) message.getPayload();
172 | labelDidChangeTo(payload.getLabel());
173 | colorDidChangeTo(LFXBinaryTypes.getLFXHSBKColorFromLXProtocolLightHsbk(payload.getColor()));
174 | powerDidChangeTo(LFXBinaryTypes.getLFXPowerStateFromLFXProtocolPowerLevel(payload.getPower()));
175 | break;
176 | }
177 | case LX_PROTOCOL_DEVICE_SET_LABEL: {
178 | LxProtocolDevice.SetLabel payload = (LxProtocolDevice.SetLabel) message.getPayload();
179 | labelDidChangeTo(payload.getLabel());
180 | break;
181 | }
182 | case LX_PROTOCOL_DEVICE_STATE_LABEL: {
183 | LxProtocolDevice.StateLabel payload = (LxProtocolDevice.StateLabel) message.getPayload();
184 | labelDidChangeTo(payload.getLabel());
185 | break;
186 | }
187 | case LX_PROTOCOL_DEVICE_SET_POWER: {
188 | LxProtocolDevice.SetPower payload = (LxProtocolDevice.SetPower) message.getPayload();
189 | powerDidChangeTo(LFXBinaryTypes.getLFXPowerStateFromLFXProtocolPowerLevel(payload.getLevel()));
190 | break;
191 | }
192 | case LX_PROTOCOL_DEVICE_STATE_POWER: {
193 | LxProtocolDevice.StatePower payload = (LxProtocolDevice.StatePower) message.getPayload();
194 | powerDidChangeTo(LFXBinaryTypes.getLFXPowerStateFromLFXProtocolPowerLevel(payload.getLevel()));
195 | break;
196 | }
197 | default:
198 | break;
199 | }
200 | }
201 |
202 | public void labelDidChangeTo(String label) {
203 | if(this.label==null || !this.label.equals(label)) {
204 | notifyListenerLabelDidChange(label);
205 | }
206 | this.label = label;
207 | }
208 |
209 | public void colorDidChangeTo(LFXHSBKColor color) {
210 | if(this.color==null || !this.color.equals(color)) {
211 | notifyListenersColorDidChange(color);
212 | }
213 | this.color = color;
214 | }
215 |
216 | public void powerDidChangeTo(LFXPowerState powerState) {
217 | if(this.powerState==null || !this.powerState.equals(powerState)) {
218 | notifyListenersPowerStateDidChange(powerState);
219 | }
220 | this.powerState = powerState;
221 | }
222 |
223 | public ArrayList getTags() {
224 | return tags;
225 | }
226 |
227 | public void setTags(ArrayList tags) {
228 | this.tags = tags;
229 | }
230 |
231 | public void setTaggedCollections(ArrayList taggedCollections) {
232 | this.taggedCollections = taggedCollections;
233 | }
234 |
235 | public void addLightListener(LFXLightListener listener) {
236 | if (!listeners.contains(listener)) {
237 | listeners.add(listener);
238 | }
239 | }
240 |
241 | public void removeAllLightListeners() {
242 | listeners.clear();
243 | }
244 |
245 | public void removeLightListener(LFXLightListener listener) {
246 | listeners.remove(listener);
247 | }
248 | }
249 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/transport_manager/gateway_connection/LFXUDPGatewayConnection.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXUDPGatewayConnection.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.transport_manager.gateway_connection;
10 |
11 | import java.net.InetAddress;
12 | import java.net.UnknownHostException;
13 | import java.util.Arrays;
14 | import java.util.HashMap;
15 | import java.util.LinkedList;
16 | import java.util.Queue;
17 | import java.util.Timer;
18 | import java.util.TimerTask;
19 |
20 | import lifx.java.android.constant.LFXSDKConstants;
21 | import lifx.java.android.entities.internal.LFXGatewayDescriptor;
22 | import lifx.java.android.entities.internal.LFXMessage;
23 | import lifx.java.android.entities.internal.structle.LxProtocol.Type;
24 | import lifx.java.android.internal.LFXWiFiObserver;
25 | import lifx.java.android.network_context.internal.transport_manager.gateway_connection.LFXSocketGeneric.SocketMessage;
26 | import lifx.java.android.network_context.internal.transport_manager.gateway_connection.LFXSocketGeneric.SocketMessageListener;
27 | import lifx.java.android.network_context.internal.transport_manager.gateway_connection.LFXSocketGeneric.SocketState;
28 | import lifx.java.android.network_context.internal.transport_manager.gateway_connection.LFXSocketGeneric.SocketStateListener;
29 | import lifx.java.android.util.LFXLog;
30 | import lifx.java.android.util.LFXNetworkUtils;
31 | import lifx.java.android.util.LFXTimerUtils;
32 |
33 | public class LFXUDPGatewayConnection extends LFXGatewayConnection implements SocketMessageListener, SocketStateListener {
34 | private final static String TAG = LFXUDPGatewayConnection.class.getSimpleName();
35 |
36 | private Queue messageOutbox;
37 | private LFXSocketGeneric socket;
38 | private Timer outboxTimer;
39 | private Timer heartbeatTimer;
40 | private Timer idleTimeoutTimer;
41 |
42 | private Runnable getHeartbeatTimerTask() {
43 | Runnable heartbeatTimerTask = new TimerTask() {
44 | public void run() {
45 | heartbeatTimerDidFire();
46 | }
47 | };
48 |
49 | return heartbeatTimerTask;
50 | }
51 |
52 | private Runnable getIdleTimerTask() {
53 | Runnable idleTimerTask = new TimerTask() {
54 | public void run() {
55 | idleTimeoutTimerDidFire();
56 | }
57 | };
58 |
59 | return idleTimerTask;
60 | }
61 |
62 | private Runnable getOutBoxTimerTask() {
63 | Runnable outBoxTimerTask = new TimerTask() {
64 | public void run() {
65 | sendNextMessageFromOutbox();
66 | }
67 | };
68 |
69 | return outBoxTimerTask;
70 | }
71 |
72 | public LFXUDPGatewayConnection(LFXGatewayDescriptor gatewayDescriptor, LFXGatewayConnectionListener listener) {
73 | super(gatewayDescriptor, listener);
74 | setConnectionState(LFXGatewayConnectionState.NOT_CONNECTED);
75 | messageOutbox = new LinkedList();
76 | outboxTimer = LFXTimerUtils.getTimerTaskWithPeriod(getOutBoxTimerTask(), LFXSDKConstants.LFX_UDP_MESSAGE_SEND_RATE_LIMIT_INTERVAL, false, "SendRateLimitTimer");
77 | socket = new LFXSocketUDP();
78 | heartbeatTimer = LFXTimerUtils.getTimerTaskWithPeriod(getHeartbeatTimerTask(), LFXSDKConstants.LFX_UDP_HEARTBEAT_INTERVAL, false, "UDPHeartbeatTimer");
79 | resetIdleTimeoutTimer();
80 | LFXLog.d(TAG, "LFXUDPGatewayConnection() - Constructor, HeartBeat, SendRate & Idle Timer Tasks");
81 | }
82 |
83 | public boolean isBroadcastConnection() {
84 | return getGatewayDescriptor().getHost().equals(LFXWiFiObserver.getWiFiBroadcastAddress());
85 | }
86 |
87 | public void heartbeatTimerDidFire() {
88 | if (isBroadcastConnection()) {
89 | return;
90 | }
91 |
92 | if (getConnectionState() == LFXGatewayConnectionState.CONNECTED) {
93 | if(getGatewayDescriptor().getPath()!=null) {
94 | LFXMessage message = LFXMessage.messageWithTypeAndPath(Type.LX_PROTOCOL_DEVICE_GET_PAN_GATEWAY, getGatewayDescriptor().getPath());
95 | sendMessage(message);
96 | }
97 | else {
98 | LFXLog.e(TAG,"heartbeatTimerDidFire() - getGatewayDescriptor().getPath()==null");
99 | }
100 | }
101 | }
102 |
103 | public void connect() {
104 | LFXLog.d(TAG, "connect() - ConnectionState: " + getConnectionState());
105 | if (getConnectionState() != LFXGatewayConnectionState.NOT_CONNECTED) {
106 | return;
107 | }
108 |
109 | LFXLog.d(TAG, "connect() - Connecting UDP Socket " + getGatewayDescriptor().getHost() + ":" + getGatewayDescriptor().getPort());
110 |
111 | try {
112 | socket.addMessageListener(this);
113 | socket.addStateListener(this);
114 | socket.connect(InetAddress.getByName(getGatewayDescriptor().getHost()).getAddress(), getGatewayDescriptor().getPort());
115 | setConnectionState(LFXGatewayConnectionState.CONNECTED);
116 | } catch (UnknownHostException e) {
117 | e.printStackTrace();
118 | }
119 | }
120 |
121 | private boolean shouldIgnoreDataFromHost(String host) {
122 | String localHost = LFXNetworkUtils.getLocalHostAddress();
123 | return localHost.equals(host);
124 | }
125 |
126 | public void sendData(byte[] data) {
127 | socket.sendMessage(new SocketMessage(data));
128 | }
129 |
130 | public void sendMessage(LFXMessage message) {
131 | LinkedList outboxAsLinkedList = (LinkedList) messageOutbox;
132 |
133 | for (int outboxIndex = 0; outboxIndex < outboxAsLinkedList.size(); outboxIndex++) {
134 | if (newMessageMakesQueuedMessageRedundant(message, outboxAsLinkedList.get(outboxIndex))) {
135 | outboxAsLinkedList.remove(outboxIndex);
136 | outboxAsLinkedList.add(outboxIndex, message);
137 | logMessageOutboxSize();
138 | return;
139 | }
140 | }
141 |
142 | messageOutbox.add(message);
143 | logMessageOutboxSize();
144 | }
145 |
146 | private void sendNextMessageFromOutbox() {
147 | LFXMessage nextMessage = messageOutbox.poll();
148 |
149 | if (nextMessage == null) {
150 | return;
151 | }
152 |
153 | byte[] messageData = nextMessage.getMessageDataRepresentation();
154 |
155 | try {
156 | socket.sendMessage(new SocketMessage(messageData, InetAddress.getByName(getGatewayDescriptor().getHost()).getAddress(), getGatewayDescriptor().getPort()));
157 | } catch (UnknownHostException e) {
158 | e.printStackTrace();
159 | }
160 | }
161 |
162 | private HashMap types = new HashMap();
163 |
164 | public void logMessageOutboxSize() {
165 | if (messageOutbox.size() > 10) {
166 | types.clear();
167 |
168 | LinkedList outboxAsLinkedList = (LinkedList) messageOutbox;
169 |
170 | for (int i = 0; i < messageOutbox.size(); i++) {
171 | String key = outboxAsLinkedList.get(i).getType().toString();
172 | Integer bla = types.get(key);
173 |
174 | if (bla == null) {
175 | bla = 0;
176 | }
177 |
178 | bla = bla + 1;
179 |
180 | types.put(key, bla);
181 | }
182 |
183 | LFXLog.w(TAG, "logMessageOutboxSize() - UDP " + getGatewayDescriptor().getHost() + " Message Outbox backlog is " + messageOutbox.size());
184 | for (String aKey : types.keySet()) {
185 | LFXLog.d(TAG,"logMessageOutboxSize()"+aKey + ": " + types.get(aKey) + ", ");
186 | }
187 |
188 | }
189 | }
190 |
191 | public void resetIdleTimeoutTimer() {
192 | if (isBroadcastConnection()) {
193 | return;
194 | }
195 |
196 | if (idleTimeoutTimer != null) {
197 | idleTimeoutTimer.cancel();
198 | idleTimeoutTimer.purge();
199 | }
200 |
201 | idleTimeoutTimer = LFXTimerUtils.getTimerTaskWithPeriod(getIdleTimerTask(), LFXSDKConstants.LFX_UDP_IDLE_TIMEOUT_INTERVAL, false, "IdleTimeoutTimer");
202 | }
203 |
204 | public void idleTimeoutTimerDidFire() {
205 | LFXLog.w(TAG, "idleTimeoutTimerDidFire() - Occurred on UDP Connection " + toString() + ", disconnecting");
206 | setConnectionState(LFXGatewayConnectionState.NOT_CONNECTED);
207 | if(getListener()!=null) getListener().gatewayConnectionDidDisconnectWithError(this, null);
208 | }
209 |
210 | private void udpSocketDidReceiveDataFromAddressWithFilterContext(LFXSocketGeneric socket, byte[] data, byte[] address, Object filterContext) {
211 | InetAddress hostAddress = null;
212 | try {
213 | hostAddress = InetAddress.getByAddress(address);
214 | } catch (UnknownHostException e) {
215 | e.printStackTrace();
216 | }
217 |
218 | if (hostAddress == null) {
219 | return;
220 | }
221 |
222 | String host = hostAddress.getHostAddress();
223 |
224 | host = LFXNetworkUtils.getIPv4StringByStrippingIPv6Prefix(host);
225 |
226 | if (!host.equals(getGatewayDescriptor().getHost()) && !isBroadcastConnection()) {
227 | return;
228 | }
229 |
230 | if (shouldIgnoreDataFromHost(host)) {
231 | return;
232 | }
233 |
234 | LFXMessage message = LFXMessage.messageWithMessageData(data);
235 |
236 | if (message == null) {
237 | LFXLog.e(TAG, "udpSocketRx() - Couldn't create message from data: " + Arrays.toString(data));
238 | return;
239 | }
240 | else {
241 | LFXLog.i(TAG, "udpSocketRx() - Got: " + message.getType().toString());
242 | }
243 |
244 | if (getListener() != null) {
245 | // NOTE: this is here to get rid of the duplicates that occur due to both the broadcast
246 | // UDP listener and gateway specific UDP listeners "receiving" the message.
247 | if (getGatewayDescriptor().getHost().equals(LFXWiFiObserver.getWiFiBroadcastAddress())) {
248 | getListener().gatewayConnectionDidReceiveMessageFromHost(this, message, host);
249 | }
250 | }
251 |
252 | resetIdleTimeoutTimer();
253 | }
254 |
255 | public void udpSocketDidCloseWithError(LFXSocketGeneric socket, String error) {
256 | setConnectionState(LFXGatewayConnectionState.NOT_CONNECTED);
257 | if(getListener()!=null) getListener().gatewayConnectionDidDisconnectWithError(this, error);
258 | }
259 |
260 | public void udpSocketDidNotConnect(LFXSocketGeneric socket, String error) {
261 | setConnectionState(LFXGatewayConnectionState.NOT_CONNECTED);
262 | if(getListener()!=null) getListener().gatewayConnectionDidDisconnectWithError(this, error);
263 | }
264 |
265 | @Override
266 | public void disconnect() {
267 | socket.close();
268 | if(heartbeatTimer!=null) {
269 | heartbeatTimer.cancel();
270 | heartbeatTimer.purge();
271 | heartbeatTimer = null;
272 | }
273 | if(outboxTimer!=null) {
274 | outboxTimer.cancel();
275 | outboxTimer.purge();
276 | outboxTimer = null;
277 | }
278 | if (idleTimeoutTimer != null) {
279 | idleTimeoutTimer.cancel();
280 | idleTimeoutTimer.purge();
281 | idleTimeoutTimer=null;
282 | }
283 | }
284 |
285 | @Override
286 | public void notifyMessageReceived(SocketMessage message) {
287 | udpSocketDidReceiveDataFromAddressWithFilterContext(null, message.getMessageData(), message.getIpAddress(), null);
288 | }
289 |
290 | @Override
291 | public void notifySocketStateChanged(LFXSocketGeneric socket, SocketState state) {
292 | switch (state) {
293 | case CONNECTED:
294 | if(getListener()!=null) getListener().gatewayConnectionDidConnect(this);
295 | break;
296 |
297 | case CONNECTING:
298 | break;
299 |
300 | case DISCONNECTED:
301 | if(getListener()!=null) getListener().gatewayConnectionDidDisconnectWithError(this, "");
302 | break;
303 | }
304 | }
305 | }
306 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/routing_table/LFXRoutingTable.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXRoutingTable.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.routing_table;
10 |
11 | import java.util.ArrayList;
12 | import java.util.HashMap;
13 |
14 | import lifx.java.android.entities.internal.LFXBinaryPath;
15 | import lifx.java.android.entities.internal.LFXBinaryTargetID;
16 | import lifx.java.android.entities.internal.LFXDeviceMapping;
17 | import lifx.java.android.entities.internal.LFXMessage;
18 | import lifx.java.android.entities.internal.LFXSiteID;
19 | import lifx.java.android.entities.internal.LFXTagMapping;
20 | import lifx.java.android.entities.internal.LFXTarget;
21 | import lifx.java.android.entities.internal.LFXBinaryTargetID.TagField;
22 | import lifx.java.android.entities.internal.structle.LxProtocolDevice;
23 | import lifx.java.android.entities.internal.structle.LxProtocolLight;
24 | import lifx.java.android.entities.internal.structle.LxProtocol.Type;
25 | import lifx.java.android.util.LFXLog;
26 |
27 | public class LFXRoutingTable {
28 | private final static String TAG = LFXRoutingTable.class.getSimpleName();
29 |
30 | private HashMap mutableDeviceMappingsByDeviceID;
31 | private ArrayList mutableTagMappings;
32 | private ArrayList mutableSiteIDs; // Could be derived from DeviceMappings, but is cached separately for performance reasons
33 |
34 | public LFXRoutingTable() {
35 | super();
36 | LFXLog.d(TAG, "LFXRoutingTable() - Constructor");
37 | mutableDeviceMappingsByDeviceID = new HashMap();
38 | mutableTagMappings = new ArrayList();
39 | mutableSiteIDs = new ArrayList();
40 | }
41 |
42 | public ArrayList getDeviceMappings() {
43 | ArrayList mappings = new ArrayList();
44 | mappings.addAll(mutableDeviceMappingsByDeviceID.values());
45 | return mappings;
46 | }
47 |
48 | public ArrayList getTagMappings() {
49 | ArrayList mappings = new ArrayList();
50 | mappings.addAll(this.mutableTagMappings);
51 | return mappings;
52 | }
53 |
54 | public ArrayList getSiteIDs() {
55 | ArrayList siteIDs = new ArrayList();
56 | siteIDs.addAll(this.mutableSiteIDs);
57 | return siteIDs;
58 | }
59 |
60 | public void updateMappingsFromMessage(LFXMessage message) {
61 | if (message.isAResponseMessage() == false) {
62 | return;
63 | }
64 |
65 | updateSiteID(message.getPath().getSiteID());
66 | updateDeviceMappingWithDeviceIDSiteID(message.getPath().getBinaryTargetID().getStringValue(), message.getPath().getSiteID());
67 |
68 | if (message.getType() == Type.LX_PROTOCOL_LIGHT_STATE) {
69 | String path = message.getPath().getBinaryTargetID().getStringValue();
70 | LFXSiteID siteID = message.getPath().getSiteID();
71 |
72 | LxProtocolLight.State payload = (LxProtocolLight.State) message.getPayload();
73 | TagField tagField = new TagField();
74 | tagField.tagData = payload.getTags().getBytes();
75 |
76 | updateDeviceMappingWithDeviceID(path, siteID, tagField);
77 | }
78 |
79 | if (message.getType() == Type.LX_PROTOCOL_DEVICE_STATE_TAGS) {
80 | String path = message.getPath().getBinaryTargetID().getStringValue();
81 | LFXSiteID siteID = message.getPath().getSiteID();
82 |
83 | LxProtocolDevice.StateTags payload = (LxProtocolDevice.StateTags) message.getPayload();
84 | TagField tagField = new TagField();
85 | tagField.tagData = payload.getTags().getBytes();
86 |
87 | updateDeviceMappingWithDeviceID(path, siteID, tagField);
88 | }
89 |
90 | if (message.getType() == Type.LX_PROTOCOL_DEVICE_STATE_TAG_LABELS) {
91 | LFXSiteID siteID = message.getPath().getSiteID();
92 |
93 | LxProtocolDevice.StateTagLabels payload = (LxProtocolDevice.StateTagLabels) message.getPayload();
94 | TagField tagField = new TagField();
95 | tagField.tagData = payload.getTags().getBytes();
96 |
97 | ArrayList singularTagFields = LFXBinaryTargetID.enumerateTagField(tagField);
98 |
99 | for (TagField aTagField : singularTagFields) {
100 | updateTagMappingWithTag(payload.getLabel(), siteID, aTagField);
101 | }
102 | }
103 | }
104 |
105 | public void updateSiteID(LFXSiteID siteID) {
106 | if (mutableSiteIDs.contains(siteID)) {
107 | return;
108 | }
109 | mutableSiteIDs.add(siteID);
110 | }
111 |
112 | public void updateDeviceMappingWithDeviceIDSiteID(String deviceID, LFXSiteID siteID) {
113 | LFXDeviceMapping deviceMapping = getDeviceMappingForDeviceID(deviceID);
114 |
115 | if (deviceMapping == null) {
116 | deviceMapping = new LFXDeviceMapping();
117 | mutableDeviceMappingsByDeviceID.put(deviceID, deviceMapping);
118 | }
119 |
120 | deviceMapping.setDeviceID(deviceID);
121 | deviceMapping.setSiteID(siteID);
122 | }
123 |
124 | public void updateDeviceMappingWithDeviceID(String deviceID, LFXSiteID siteID, TagField tagField) {
125 | LFXDeviceMapping deviceMapping = getDeviceMappingForDeviceID(deviceID);
126 |
127 | if (deviceMapping == null) {
128 | deviceMapping = new LFXDeviceMapping();
129 | mutableDeviceMappingsByDeviceID.put(deviceID, deviceMapping);
130 | }
131 |
132 | deviceMapping.setDeviceID(deviceID);
133 | deviceMapping.setSiteID(siteID);
134 | deviceMapping.setTagField(tagField);
135 | }
136 |
137 | public void updateTagMappingWithTag(String tag, LFXSiteID siteID, TagField tagField) {
138 | if (siteID.isZeroSite()) {
139 | return;
140 | }
141 |
142 | LFXTagMapping tagMapping = getTagMappingForSiteIDAndTagField(siteID, tagField);
143 |
144 | if (tag.length() > 0) {
145 | if (tagMapping == null) {
146 | tagMapping = new LFXTagMapping();
147 | mutableTagMappings.add(tagMapping);
148 | }
149 |
150 | tagMapping.setTag(tag);
151 | tagMapping.setSiteID(siteID);
152 | tagMapping.setTagField(tagField);
153 | } else {
154 | if (tagMapping != null) {
155 | mutableTagMappings.remove(tagMapping);
156 | }
157 | }
158 | }
159 |
160 | public void resetRoutingTable() {
161 | mutableDeviceMappingsByDeviceID.clear();
162 | mutableTagMappings.clear();
163 | mutableSiteIDs.clear();
164 | }
165 |
166 | public ArrayList getAllTags() {
167 | ArrayList allTags = new ArrayList();
168 |
169 | for (LFXTagMapping aTagMapping : mutableTagMappings) {
170 | allTags.add(aTagMapping.getTag());
171 | }
172 |
173 | return allTags;
174 | }
175 |
176 | @SuppressWarnings("unchecked")
177 | public ArrayList getAllSiteIDs() {
178 | return (ArrayList) mutableSiteIDs.clone();
179 | }
180 |
181 | public LFXDeviceMapping getDeviceMappingForDeviceID(String deviceID) {
182 | return mutableDeviceMappingsByDeviceID.get(deviceID);
183 | }
184 |
185 | public ArrayList getDeviceMappingsForSiteID(LFXSiteID siteID) {
186 | ArrayList deviceMappings = new ArrayList();
187 |
188 | for (LFXDeviceMapping aDeviceMapping : mutableDeviceMappingsByDeviceID.values()) {
189 | if (aDeviceMapping.getSiteID().equals(siteID)) {
190 | deviceMappings.add(aDeviceMapping);
191 | }
192 | }
193 |
194 | return deviceMappings;
195 | }
196 |
197 | public ArrayList getDeviceMappingsForSiteIDTagField(LFXSiteID siteID, TagField tagField) {
198 | ArrayList deviceMappings = new ArrayList();
199 |
200 | for (LFXDeviceMapping aDeviceMapping : mutableDeviceMappingsByDeviceID.values()) {
201 | if (aDeviceMapping.getSiteID().equals(siteID) && aDeviceMapping.getTagField().equals(tagField)) {
202 | deviceMappings.add(aDeviceMapping);
203 | }
204 | }
205 |
206 | return deviceMappings;
207 | }
208 |
209 | public LFXTagMapping getTagMappingForSiteIDAndTagField(LFXSiteID siteID, TagField tagField) {
210 | for (LFXTagMapping aTagMapping : mutableTagMappings) {
211 | if (aTagMapping.getSiteID().equals(siteID) &&
212 | aTagMapping.getTagField().equals(tagField)) {
213 | return aTagMapping;
214 | }
215 | }
216 |
217 | return null;
218 | }
219 |
220 | public ArrayList getTagMappingsForTag(String tag) {
221 | ArrayList tagMappings = new ArrayList();
222 |
223 | for (LFXTagMapping aTagMapping : mutableTagMappings) {
224 | if (aTagMapping.getTag().equals(tag)) {
225 | tagMappings.add(aTagMapping);
226 | }
227 | }
228 |
229 | return tagMappings;
230 | }
231 |
232 | public ArrayList getBinaryPathsForTarget(LFXTarget target) {
233 | ArrayList returnPaths = new ArrayList();
234 |
235 | switch (target.getTargetType()) {
236 | case BROADCAST: {
237 | for (LFXSiteID aSiteID : mutableSiteIDs) {
238 | LFXBinaryPath path = LFXBinaryPath.getPathWithSiteIDAndTargetID(aSiteID, LFXBinaryTargetID.getBroadcastTargetID());
239 | returnPaths.add(path);
240 | }
241 |
242 | break;
243 | }
244 | case DEVICE: {
245 | // If we know what site the device is in, send it there, otherwise
246 | // send to each
247 | LFXDeviceMapping deviceMapping = getDeviceMappingForDeviceID(target.getDeviceID());
248 |
249 | if (deviceMapping != null) {
250 | LFXBinaryPath binaryPath = LFXBinaryPath.getPathWithSiteIDAndTargetID(deviceMapping.getSiteID(), LFXBinaryTargetID.getDeviceTargetIDWithString(target.getDeviceID()));// targetID:[LFXBinaryTargetID deviceTargetIDWithString:target.deviceID]];
251 | returnPaths.add(binaryPath);
252 | break;
253 | }
254 |
255 | for (LFXSiteID aSiteID : mutableSiteIDs) {
256 | LFXBinaryPath binaryPath = LFXBinaryPath.getPathWithSiteIDAndTargetID(aSiteID, LFXBinaryTargetID.getDeviceTargetIDWithString(target.getDeviceID()));
257 | returnPaths.add(binaryPath);
258 | // TODO: decide if to // break; here
259 | }
260 | }
261 | case TAG: {
262 | // Look up the Tag Mappings
263 | for (LFXTagMapping aTagMapping : getTagMappingsForTag(target.getTag())) {
264 | LFXBinaryTargetID targetID = LFXBinaryTargetID.getGroupTargetIDWithTagField(aTagMapping.getTagField());
265 | LFXBinaryPath binaryPath = LFXBinaryPath.getPathWithSiteIDAndTargetID(aTagMapping.getSiteID(), targetID);
266 | returnPaths.add(binaryPath);
267 | }
268 | }
269 | }
270 |
271 | return returnPaths;
272 | }
273 |
274 | public ArrayList getDeviceIDsForBinaryPath(LFXBinaryPath binaryPath) {
275 | switch (binaryPath.getBinaryTargetID().getTargetType()) {
276 | case BROADCAST: {
277 | ArrayList deviceIds = new ArrayList();
278 |
279 | for (LFXDeviceMapping aDeviceMapping : getDeviceMappingsForSiteID(binaryPath.getSiteID())) {
280 | deviceIds.add(aDeviceMapping.getDeviceId());
281 | }
282 |
283 | return deviceIds;
284 | }
285 | case DEVICE: {
286 | ArrayList deviceIds = new ArrayList();
287 | deviceIds.add(binaryPath.getBinaryTargetID().getStringValue());
288 | return deviceIds;
289 | }
290 | case TAG: {
291 | ArrayList deviceIds = new ArrayList();
292 |
293 | for (LFXDeviceMapping aDeviceMapping : getDeviceMappingsForSiteIDTagField(binaryPath.getSiteID(), binaryPath.getBinaryTargetID().getGroupTagField())) {
294 | deviceIds.add(aDeviceMapping.getDeviceId());
295 | }
296 |
297 | return deviceIds;
298 | }
299 | }
300 |
301 | return new ArrayList();
302 | }
303 |
304 | public ArrayList getTagMappingsForSiteIDAndTag(LFXSiteID siteID, String tag) {
305 | ArrayList mappings = new ArrayList();
306 |
307 | for (LFXTagMapping aMapping : mutableTagMappings) {
308 | if (aMapping.getSiteID().equals(siteID) && aMapping.getTag().equals(tag)) {
309 | mappings.add(aMapping);
310 | }
311 | }
312 |
313 | return mappings;
314 | }
315 | }
316 |
--------------------------------------------------------------------------------
/library/src/lifx/java/android/network_context/internal/transport_manager/lan/LFXLANTransportManager.java:
--------------------------------------------------------------------------------
1 | //
2 | // LFXLANTransportManager.java
3 | // LIFX
4 | //
5 | // Created by Jarrod Boyes on 24/03/14.
6 | // Copyright (c) 2014 LIFX Labs. All rights reserved.
7 | //
8 |
9 | package lifx.java.android.network_context.internal.transport_manager.lan;
10 |
11 | import java.util.ArrayList;
12 | import java.util.HashMap;
13 | import java.util.HashSet;
14 | import java.util.Set;
15 |
16 | import lifx.java.android.entities.internal.LFXGatewayDescriptor;
17 | import lifx.java.android.entities.internal.LFXMessage;
18 | import lifx.java.android.entities.internal.LFXSiteID;
19 | import lifx.java.android.entities.internal.structle.LxProtocolDevice.Service;
20 | import lifx.java.android.network_context.internal.transport_manager.LFXTransportManager;
21 | import lifx.java.android.network_context.internal.transport_manager.gateway_connection.LFXGatewayConnection;
22 | import lifx.java.android.network_context.internal.transport_manager.gateway_connection.LFXGatewayConnection.LFXGatewayConnectionListener;
23 | import lifx.java.android.network_context.internal.transport_manager.gateway_connection.LFXGatewayConnection.LFXGatewayConnectionState;
24 | import lifx.java.android.network_context.internal.transport_manager.lan.gateway_discovery.LFXGatewayDiscoveryController;
25 | import lifx.java.android.network_context.internal.transport_manager.lan.gateway_discovery.LFXGatewayDiscoveryTableEntry;
26 | import lifx.java.android.network_context.internal.transport_manager.lan.gateway_discovery.LFXGatewayDiscoveryController.LFXGatewayDiscoveryControllerListener;
27 | import lifx.java.android.network_context.internal.transport_manager.lan.gateway_discovery.LFXGatewayDiscoveryController.LFXGatewayDiscoveryMode;
28 | import lifx.java.android.util.LFXLog;
29 | import lifx.java.android.util.LFXNetworkUtils;
30 | import lifx.java.android.util.LFXTimerUtils;
31 |
32 | public class LFXLANTransportManager extends LFXTransportManager implements LFXGatewayConnectionListener, LFXGatewayDiscoveryControllerListener {
33 | private final static String TAG = LFXLANTransportManager.class.getSimpleName();
34 |
35 | private LFXGatewayConnection broadcastUDPConnection;
36 | private LFXGatewayConnection peerToPeerUDPConnection;
37 |
38 | private LFXGatewayDiscoveryController gatewayDiscoveryController;
39 |
40 | private HashMap gatewayConnections;
41 |
42 | private boolean enabled = true;
43 |
44 | public void disconnect() {
45 | enabled = false;
46 |
47 | broadcastUDPConnection.disconnect();
48 | broadcastUDPConnection.setListener(null);
49 | peerToPeerUDPConnection.disconnect();
50 | peerToPeerUDPConnection.setListener(null);
51 | gatewayDiscoveryController.shutDown();
52 |
53 | for (LFXGatewayConnection aGatewayConnection : gatewayConnections.values()) {
54 | aGatewayConnection.disconnect();
55 | aGatewayConnection.setListener(null);
56 | }
57 |
58 | gatewayConnections.clear();
59 | }
60 |
61 | public LFXLANTransportManager() {
62 | super();
63 | LFXLog.d(TAG, "LFXLANTransportManager() - Constructor");
64 | }
65 |
66 | public void connect() {
67 | enabled = true;
68 |
69 | gatewayDiscoveryController = LFXGatewayDiscoveryController.getGatewayDiscoveryControllerWithLANTransportManager(this, this);
70 | gatewayConnections = new HashMap();
71 |
72 | LFXLog.d(TAG, "connect() - Setup UDP Connections");
73 | setupBroadcastUDPConnection();
74 | setupPeerToPeerUDPConnection();
75 |
76 | LFXLog.d(TAG, "connect() - Start Discovery");
77 | gatewayDiscoveryController.setDiscoveryMode(LFXGatewayDiscoveryMode.ACTIVELY_SEARCHING);
78 | gatewayDiscoveryController.sendGatewayDiscoveryMessage();
79 | }
80 |
81 | public void setupBroadcastUDPConnection() {
82 | LFXLog.d(TAG, "setupBroadcastUDPConnection()");
83 | if(broadcastUDPConnection!=null) {
84 | broadcastUDPConnection.disconnect();
85 | broadcastUDPConnection.setListener(null);
86 | }
87 | broadcastUDPConnection = LFXGatewayConnection.getGatewayConnectionWithGatewayDescriptor(LFXGatewayDescriptor.getBroadcastGatewayDescriptor(), this);
88 | broadcastUDPConnection.connect();
89 | }
90 |
91 | public void setupPeerToPeerUDPConnection() {
92 | LFXLog.d(TAG, "setupPeerToPeerUDPConnection()");
93 | if(peerToPeerUDPConnection!=null) {
94 | peerToPeerUDPConnection.disconnect();
95 | peerToPeerUDPConnection.setListener(null);
96 | }
97 | peerToPeerUDPConnection = LFXGatewayConnection.getGatewayConnectionWithGatewayDescriptor(LFXGatewayDescriptor.getClientPeerToPeerGatewayDescriptor(), this);
98 | peerToPeerUDPConnection.connect();
99 | }
100 |
101 | public void connectionStatesDidChange() {
102 | if (enabled) {
103 | LFXLog.d(TAG, "connectionStatesDidChange()");
104 |
105 | boolean newIsConnected = false;
106 | for (LFXGatewayConnection aGatewayConnection : gatewayConnections.values()) {
107 | LFXLog.d(TAG,"connectionStatesDidChange() - "+aGatewayConnection.getGatewayDescriptor().toString() + " : " + aGatewayConnection.getConnectionState().toString());
108 |
109 | if (aGatewayConnection.getConnectionState() == LFXGatewayConnectionState.CONNECTED) {
110 | newIsConnected = true;
111 | }
112 | }
113 |
114 | setIsConnected(newIsConnected);
115 |
116 | gatewayDiscoveryController.setDiscoveryMode(isConnected() ? LFXGatewayDiscoveryMode.NORMAL : LFXGatewayDiscoveryMode.ACTIVELY_SEARCHING);
117 | }
118 | }
119 |
120 | public void sendMessage(LFXMessage message) {
121 | LFXLog.i(TAG, "sendMessage() - " + message.getType().toString());
122 | if (message.getPath().getSiteID().isZeroSite()) {
123 | for (String aGatewayHost : getGatewayHosts()) {
124 | //LFXGatewayConnection tcpConnection = getGatewayConnectionForHost(aGatewayHost, Service.LX_PROTOCOL_DEVICE_SERVICE_TCP);
125 | LFXGatewayConnection udpConnection = getGatewayConnectionForHost(aGatewayHost, Service.LX_PROTOCOL_DEVICE_SERVICE_UDP);
126 |
127 | if(udpConnection!=null) {
128 | sendMessageOnConnection(message, udpConnection);
129 | }
130 | else {
131 | LFXLog.e(TAG,"sendMessage() - No connection?");
132 | }
133 |
134 |
135 | // CAKEY123445 - No TCP Support so removed transport
136 |
137 | // ArrayList connections = new ArrayList();
138 | //
139 | // if (tcpConnection != null) {
140 | // connections.add(tcpConnection);
141 | // }
142 | //
143 | // if (udpConnection != null) {
144 | // connections.add(udpConnection);
145 | // }
146 | //
147 | // LFXGatewayConnection connectionToUse = null;
148 | //
149 | // if (connections.size() > 0) {
150 | // connectionToUse = connections.get(0);
151 | // }
152 | //
153 | // if (connectionToUse != null) {
154 | // sendMessageOnConnection(message, connectionToUse);
155 | // }
156 | }
157 | }
158 | else {
159 | boolean messageWasSent = false;
160 | for (String aGatewayHost : getGatewayHostsForSiteID(message.getPath().getSiteID())) {
161 | //LFXGatewayConnection tcpConnection = getGatewayConnectionForHost(aGatewayHost, Service.LX_PROTOCOL_DEVICE_SERVICE_TCP);
162 | LFXGatewayConnection udpConnection = getGatewayConnectionForHost(aGatewayHost, Service.LX_PROTOCOL_DEVICE_SERVICE_UDP);
163 |
164 | if(udpConnection!=null) {
165 | sendMessageOnConnection(message, udpConnection);
166 | messageWasSent = true;
167 | }
168 |
169 | // CAKEY123445 - No TCP Support so removed transport
170 |
171 | // ArrayList connections = new ArrayList();
172 | // if (message.prefersUDPOverTCP()) {
173 | // if (udpConnection != null) {
174 | // connections.add(udpConnection);
175 | // }
176 | //
177 | // if (tcpConnection != null) {
178 | // connections.add(tcpConnection);
179 | // }
180 | // } else {
181 | // if (tcpConnection != null) {
182 | // connections.add(tcpConnection);
183 | // }
184 | //
185 | // if (udpConnection != null) {
186 | // connections.add(udpConnection);
187 | // }
188 | // }
189 | //
190 | // LFXGatewayConnection connectionToUse = null;
191 | //
192 | // if (connections.size() > 0) {
193 | // connectionToUse = connections.get(0);
194 | // }
195 | //
196 | // if (connectionToUse != null) {
197 | // sendMessageOnConnection(message, connectionToUse);
198 | // messageWasSent = true;
199 | // }
200 | }
201 |
202 | if (!messageWasSent) {
203 | sendMessageOnConnection(message, broadcastUDPConnection);
204 | }
205 | }
206 |
207 | sendObserverCallbacksForMessage(message);
208 | }
209 |
210 | public void sendBroadcastUDPMessage(LFXMessage message) {
211 | sendMessageOnConnection(message, broadcastUDPConnection);
212 | sendObserverCallbacksForMessage(message);
213 | }
214 |
215 | public void sendMessageOnConnection(LFXMessage message, LFXGatewayConnection connection) {
216 | if (connection != null) {
217 | connection.sendMessage((LFXMessage) message.clone());
218 | }
219 | }
220 |
221 | public ArrayList getGatewayDescriptorsForSiteID(LFXSiteID siteID) {
222 | ArrayList descriptors = new ArrayList();
223 |
224 | for (LFXGatewayDescriptor key : gatewayConnections.keySet()) {
225 | if (key.getPath().getSiteID().equals(siteID)) {
226 | descriptors.add(key);
227 | }
228 | }
229 |
230 | return descriptors;
231 | }
232 |
233 | public Set getGatewayHostsForSiteID(LFXSiteID siteID) {
234 | ArrayList descriptors = getGatewayDescriptorsForSiteID(siteID);
235 | ArrayList hosts = new ArrayList();
236 | for (LFXGatewayDescriptor aDescriptor : descriptors) {
237 | hosts.add(aDescriptor.getHost());
238 | }
239 |
240 | return new HashSet(hosts);
241 | }
242 |
243 | public Set getGatewayHosts() {
244 | ArrayList hosts = new ArrayList();
245 |
246 | for (LFXGatewayDescriptor key : gatewayConnections.keySet()) {
247 | hosts.add(key.getHost());
248 | }
249 |
250 | return new HashSet(hosts);
251 | }
252 |
253 | public LFXGatewayConnection getGatewayConnectionForHost(String host, Service service) {
254 | for (LFXGatewayConnection aConnection : gatewayConnections.values()) {
255 | if (aConnection.getGatewayDescriptor().getHost().equals(host) &&
256 | aConnection.getGatewayDescriptor().getService() == service) {
257 | return aConnection;
258 | }
259 | }
260 |
261 | return null;
262 | }
263 |
264 | public void gatewayConnectionDidConnect(LFXGatewayConnection connection) {
265 | connectionStatesDidChange();
266 | listener.transportManagerDidConnectToGateway(this, connection.getGatewayDescriptor());
267 | }
268 |
269 | public void gatewayConnectionDidDisconnectWithError(LFXGatewayConnection connection, String error) {
270 | if (connection == broadcastUDPConnection) {
271 | broadcastUDPConnection.disconnect();
272 | broadcastUDPConnection.setListener(null);
273 | broadcastUDPConnection=null;
274 |
275 | if (enabled) {
276 | Runnable task = new Runnable() {
277 | @Override
278 | public void run() {
279 | setupBroadcastUDPConnection();
280 | }
281 | };
282 |
283 | LFXTimerUtils.scheduleDelayedTask(task, 1000);
284 | LFXLog.i(TAG, "gatewayConnectionDidDisconnectWithError() - Removed broadcastUDPConnection & deferred restart");
285 | }
286 | else {
287 | LFXLog.i(TAG,"gatewayConnectionDidDisconnectWithError() - Removed broadcastUDPConnection");
288 | }
289 | } else if (connection == peerToPeerUDPConnection) {
290 | peerToPeerUDPConnection.disconnect();
291 | peerToPeerUDPConnection.setListener(null);
292 | peerToPeerUDPConnection=null;
293 |
294 | if (enabled) {
295 | Runnable task = new Runnable() {
296 | @Override
297 | public void run() {
298 | setupPeerToPeerUDPConnection();
299 | }
300 | };
301 |
302 | LFXTimerUtils.scheduleDelayedTask(task, 3000);
303 | LFXLog.i(TAG, "gatewayConnectionDidDisconnectWithError() - Removed peerToPeerUDPConnection & deferred restart");
304 | }
305 | else {
306 | LFXLog.i(TAG,"gatewayConnectionDidDisconnectWithError() - Removed peerToPeerUDPConnection");
307 | }
308 | } else {
309 | gatewayConnections.remove(connection.getGatewayDescriptor());
310 | connection.disconnect();
311 | connection.setListener(null);
312 | LFXLog.i(TAG, "gatewayConnectionDidDisconnectWithError() - Removed other???");
313 | }
314 |
315 | connectionStatesDidChange();
316 | listener.transportManagerDidDisconnectFromGateway(this, connection.getGatewayDescriptor());
317 | }
318 |
319 | public void gatewayConnectionDidReceiveMessageFromHost(LFXGatewayConnection connection, LFXMessage message, String host) {
320 | host = LFXNetworkUtils.getIPv4StringByStrippingIPv6Prefix(host);
321 |
322 | message.setGatewayDescriptor(connection.getGatewayDescriptor());
323 | message.setSourceNetworkHost(host);
324 | sendObserverCallbacksForMessage(message);
325 | }
326 |
327 | public void gatewayDiscoveryControllerDidUpdateEntry(LFXGatewayDiscoveryController table, LFXGatewayDiscoveryTableEntry tableEntry, boolean entryIsNew) {
328 | LFXGatewayDescriptor gateway = tableEntry.getGatewayDescriptor();
329 |
330 | if (gateway.getPort() == 0) {
331 | return;
332 | }
333 |
334 | LFXGatewayConnection existingConnection = null;
335 |
336 | for (LFXGatewayDescriptor aDescriptor : gatewayConnections.keySet()) {
337 | if (aDescriptor.toString().equals(gateway.toString())) {
338 | existingConnection = gatewayConnections.get(aDescriptor);
339 | }
340 | }
341 |
342 | if (existingConnection == null) {
343 | LFXGatewayConnection newConnection = LFXGatewayConnection.getGatewayConnectionWithGatewayDescriptor(gateway, this);
344 | newConnection.connect();
345 | gatewayConnections.put(gateway, newConnection);
346 | connectionStatesDidChange();
347 | }
348 | }
349 | }
350 |
--------------------------------------------------------------------------------