Getting Ready for the Holiday Season with Phillips Hue and a Raspberry Pi

The holiday season is upon us; by the end of this month I expect to start seeing my neighbors put out their fall decorations. By mid-October decorations for Halloween will show up. After Halloween the decorations roll back to fall themed only and then are changed to Christmas decorations right after new years. Two of these holidays tend to come with flashy displays and lights: Halloween and Christmas.

porch

I primarily use Phillips Hue lighting throughout my house and it is a perfect companion for festive displays. The color bulbs are adaptable to any color scheme and the newly released Edison-style bulbs add a warm glow to fall scenes.  The Phillips Hue lighting sets are programmable if you are using a hub. While the new light bulbs have Bluetooth support to directly be controlled by a phone there’s not public API for them (yet). For programming a hub is needed.

pumpkin

I’ve written on controlling the Phillips Hue lights before. Expanding on that I wanted to make a project that would let an IoT device trigger a scene according to some external event. I’ll use a motion sensor to trigger the relevant events.

 

But you could also use sound, change in temperature, lighting, or time as sources. I’ll be using a Raspberry Pi; it has network connectivity and can be easily interfaced to a number of devices.  I’m using the Raspberry Pi zero but about any Pi will do. Hue does have available a motion sensor ; if one only wishes to control lights based on motion a solution is available. But if one wishes to have other triggers or trigger other actions along with the lights a custom solution is needed.

20191005_160504.jpg

The Raspberry Pi 4 with a heat sink attached.

20191005_161532.jpg

Raspberry Pi Zero with a 4-port USB hub

All that I want to happen is for the the lighting pattern to change when a person is detected. I’ll use a passive infrared sensor for presence detection.  For Halloween I want a Hue light that is illuminating a jack-o-lantern to pulsate an orange color. When someone comes up knock on the door I want the light for the front door to go bright white. A few moments after a person is no longer there I want the system to go back to it’s previous pattern. But past a certain hour I don’t want this to continue; after 10:00pm the lights should extinguish. Simple enough, right?

 

20191005_155936.jpg

This is the passive infrared sensor that I used.

The physical build for this circuit is easy. The Passive Infrared Sensor (PIR) will get power from the VCC and ground pins of the Raspberry Pi. The signal line from the PIR can be connected to any of the GPIO pins. I’m going to use pin 3. The circuit will need to be put in an enclosure to protect it from rain or humidity in general. If your enclosure doesn’t already have a weather protected way to get power in your options are to either run the Pi off of a battery that is within the enclosure  (that means periodic recharging) or drill a hole for the wires yourself and apply a sealant.

There are a lot of languages that I could use for writing my program on the Pi. Python, Java, and C/C++ make the top of the list (in no specific order). For this project I’ve decided to go with Java. To interact with the pins in Java we will need to import classes from com.pi4j.io and com.pi4j.wiringpi. These are not standard libraries; they exists to provide an interface to the pins. To demonstrate reading a pin in Java here is a simple program that will print text in a look that reflects the pin state.

import com.pi4j.io.*;
import com.pi4j.wiringpi.Gpio;
import com.pi4j.wiringpi.GpioUtil;

public class PinTest {
   public static void main(String args[]) throws InterruptedException {   
      final GpioController gpio = GpioFactory.getInstance();
      Gpio.pinMode (3, Gpio.INPUT) ;          
      while(true) {
         if (Gpio.digitalRead(3) == 0){
               System.out.println(The Pin is ON");
         }else{
            System.out.println("The Pin is OFF");
         }
      }
   }
}

Phillips has an SDK for Java. You might see it present as an SDK for Android, but it works fine in other Java environments. A convenience from this is that a significant portion of the development can be done on your computer of choice. I did most of the development on a Mac and used git to transfer it to the Raspberry Pi when done.

20191005_162433.jpg

The color Hue lighting can take on a variety of colors.

The overall execution loop of the program will check whether or not the trigger condition has occurred. If the trigger condition has occurred then the program will activate a scene. If not then it deactivates the scene. The program loop also contains some debouncing logic. Depending on the type of sensor used and the sensors characteristics a sensor could change states with ever cycle. I’ve chosen to only deactivate if a certain amount of time has passed since the last activation. For initial development instead of interfacing to an actual sensor I have a method that is returning a random Boolean value. When the code is moved to the Raspberry Pi this method will be updated to read the state of the actual sensor. The following will only deactivate after there have been 2 seconds with no activation event.

    boolean getActivationState() { 
        return random.nextBoolean();
    }

    void runLoop() throws InterruptedException{ 
        System.out.println("running");
        long lastActivation = System.currentTimeMillis();
        while(true) { 
            Thread.sleep(100);
            boolean isActivated = getActivationState();
            if(isActivated) {
                lastActivation = System.currentTimeMillis();
                activateScene();
            }
            else {
                long now = System.currentTimeMillis();
                if ((now - lastActivation)> 2000)
                    deactivateScene();
            }
        }
    }

Controlling the lights happens through the Hue SDK. Before activating the lights the Hue bridge must be discovered. While Hue makes a series of lights that have Bluetooth controllers built in and can be controlled without the Hue Bridge currently they only support APIs through the bridge. It is a required hardware component.

The SDK already contains functions for discovering the bridge. All that a developer needs to do is initiate a search and implement a callback object that will receive information on the bridges discovered. In the following I instantiate the Phillips Hue SDK object and register a listener.  If the program had been connected with a bridge before the IP address if that bridge is loaded and it reconnects to it. Otherwise the search is initiated. As the search occurs the earlier registered listener receives callbacks.

private void init() {
    this.loadSettings();
    System.out.println("Getting SDK instance");
    phHueSDK = PHHueSDK.create();
    System.out.println("Setting App Name");
    phHueSDK.setAppName("HolidayLights");
    phHueSDK.setDeviceName("RaspPi");
    System.out.println("SDK initialized");
    phHueSDK.getNotificationManager().registerSDKListener(listener);

    if(this.getLastIpAddress()  != null) {
        System.out.println("Connect to last access point");
        PHAccessPoint lastAccessPoint = new PHAccessPoint();
        lastAccessPoint.setIpAddress(getLastIpAddress());
        lastAccessPoint.setUsername(getUserName());
        if (!phHueSDK.isAccessPointConnected(lastAccessPoint)) {
            phHueSDK.connect(lastAccessPoint);
        }
    } else {
        System.out.println("Searching for access point");
        PHBridgeSearchManager sm = (PHBridgeSearchManager) phHueSDK.getSDKService(PHHueSDK.SEARCH_BRIDGE);
        // Start the UPNP Searching of local bridges.
        sm.search(true, true);
    }
}

The listener is of type PHSDKListener. I won’t show the full implementation here but will show some of the more relevant parts.

When the bridges are found they are returned as a list. I’ve only got one on my home network and so I connect to the first one seen. If you have more than one bridge you’ll need to implement your own logic for making a selection.

@Override
public void onAccessPointsFound(List accessPoint) {
    System.out.println("Access point found");
    if (accessPoint != null && accessPoint.size() > 0) {
        System.out.println("Number of access points: "+new Integer(accessPoint.size()).toString());
        phHueSDK.getAccessPointsFound().clear();
        phHueSDK.getAccessPointsFound().addAll(accessPoint);      
        phHueSDK.connect(accessPoint.get(0));       
    }
}

When the connect attempt is made it is necessary to press the pairing button on the bridge. The console will print a message from the SDK saying this.  Once the bridge is connected I save an instance of the bridge and the a

 

 

        @Override
        public void onBridgeConnected(PHBridge b, String username) {
            HolidayController.this.bridge = b;
            isBridgeConnected = true;
            System.out.println("on bridge connected...");
            phHueSDK.setSelectedBridge(b);
            phHueSDK.enableHeartbeat(b, PHHueSDK.HB_INTERVAL);
            phHueSDK.getLastHeartbeat().put(b.getResourceCache().getBridgeConfiguration() .getIpAddress(), System.currentTimeMillis());
            setLastIpAddress(b.getResourceCache().getBridgeConfiguration().getIpAddress());
            setUserName(username);
        }

After the bridge connects the SDK will query the state of the lights on the system and update some objects representing the last known state of each light. The first time the cache is updated the program prints the name of each light and the light’s identity. This information is useful for selecting which lights will be controlled.  The light list is saved for the program to use.

        @Override
        public void onCacheUpdated(List<Integer> arg0, PHBridge bridge) {
            if(!isDeviceListPrinted) {
                PHBridgeResourcesCache rc = bridge.getResourceCache();
                List<PHLight> lightList = rc.getAllLights();
                HolidayController.this.lightList = lightList;
                ListIterator<PHLight> it = lightList.listIterator();
                while(it.hasNext()) {
                    PHLight l = it.next();
                    System.out.println(l.getIdentifier() + "    " + l.getName());
                }
                isDeviceListPrinted = true;
            }
        }
With that in place we now have enough information to change the state of the lights. To test things out I started with implementations of activateScene and deactivateScene that will just turn all the Hue lights on and off (don’t do this if you have other people in your dwelling that this would affect).
void activateScene() {
    ListIterator<PHLight> it = lightList.listIterator();
    while(it.hasNext()) {
        PHLight l = it.next();
        System.out.println(l.getIdentifier() + "    " + l.getName());
        PHLightState state = l.getLastKnownLightState();
        state.setOn(true);
        state.setBrightness(254);
        float[] xy = PHUtilities.calculateXYFromRGB(
            0xFF & ((int)color>> 0x10), 
            0xFF & ((int)color >> (long)0x08), 
            0xFF & (int)color, l.getModelNumber());
        l.setLastKnownLightState(state);
    
        bridge.updateLightState(l.getIdentifier(), state,  NOPListener);
    }
    isDeviceListPrinted = true;
}

void deactivateScene() {
    ListIterator<PHLight> it = lightList.listIterator();
    while(it.hasNext()) {
        PHLight l = it.next();
        System.out.println(l.getIdentifier() + "    " + l.getName());
        PHLightState state = l.getLastKnownLightState();
        state.setOn(false);
        //state.setBrightness(254);
        l.setLastKnownLightState(state);
    
        this.bridge.updateLightState(l.getIdentifier(), state,  NOPListener);
    }
    isDeviceListPrinted = true;
}
If the program is run at this point the lights will turn on and off somewhat randomly. Ultimately we don’t want it to control all the lights. Instead I want to be able to specify the lights that it is going to control. I’ve made a JSON file file that contains a couple of elements. One is the RGB color that I want to use in the form of an integer, the other is an array of numbers where each number is an ID for the light to be controlled. The RGB color is specified here as a base 10 number instead of the normal base 16 that you may see used for RGB codes. Unfortunately JSON doesn’t support hexadecimal numbers 🙁.
{
    "lights":[5, 7, 9],
    "color": 16711935
}
These values are read by the code. Before the code acts on any light it checks to see if its identifier is in this array before continuing. During activation if the identifier is in the array the light’s state is set to on, brightness is set to full, and the color is applied. The color must be converted to the right color space before being applied to the light; something that is done with a utility function that the SDK provides.
void activateScene() {
    System.out.println("activating scene");
    ListIterator<PHLight> it = lightList.listIterator();
    while(it.hasNext()) {
        PHLight l = it.next();
        if(isTargetLight(l.getIdentifier())) {
            System.out.println(l.getIdentifier() + "    " + l.getName());
            PHLightState state = l.getLastKnownLightState();
            state.setOn(true);
            state.setBrightness(254);
            float[] xy = PHUtilities.calculateXYFromRGB(
                0xFF & ((int)color>> 0x10), 
                0xFF & ((int)color >> (long)0x08), 
                0xFF & (int)color, l.getModelNumber()
            );
            state.setX(xy[0]);
            state.setY(xy[1]);
            l.setLastKnownLightState(state);        
            bridge.updateLightState(l.getIdentifier(), state,  NOPListener);
        }
    }
}

void deactivateScene() {
    System.out.println("deactivating");
    ListIterator<PHLight> it = lightList.listIterator();
    while(it.hasNext()) {
        PHLight l = it.next();
        if(isTargetLight(l.getIdentifier())) {
        System.out.println(l.getIdentifier() + "    " + l.getName());
        PHLightState state = l.getLastKnownLightState();
        state.setOn(false);
        l.setLastKnownLightState(state);
    
        this.bridge.updateLightState(l.getIdentifier(), state,  NOPListener);
        }
    }
}
The last steps needed to make the device work as intended are to update the getActivationState() function to read the actual state of the motion sensor instead of a random value and wiring the motion sensor to a Raspberry Pi. From hereon the code is only going to work on a Raspberry Pi since the libraries for reading the pins are only applicable to this device. It is possible to dynamically load class libraries and use them as needed for the specific platform on which code is running. But information on doing that is beyond the scope of what I wish to discuss here.
I’m declaring a GpioController variable at the class level and am instantiating it in the constructor. I also set the mode of the IO pin that I’ll be using to  input.
    GpioController gpio;
    
    HolidayController() {
        gpio = GpioFactory.getInstance();
        Gpio.pinMode (3, Gpio.INPUT) ; 
        //....
     }
The getActivationState() implementation only needs to contain a single line.
boolean getActivationState() { 
   return Gpio.digitalRead(3);
}
With that change it will now work. If the Raspberry Pi is placed in a position where the motion sensor has a view of the space of interest then it will control the lights. If you are using one of the earlier Raspberry Pis (anything before the Raspberry Pi 4) you should be able to also power the Pi off of a portable phone charger; there are many that will make sufficient batteries for the Pi. The Raspberry Pi 4 has higher energy requirements and you may run into more challenges finding a portable power supply that works.
Why use the Pi at all for this? Because there is a lot of room to expand. Such as using the video capabilities of the pi to power a display or controlling other devices. Controlling the lights is a start. I’ll be revisiting this project for add-ons in the future.
If you want to start on something similar yourself the following (affiliate) links will take you to the products on Amazon.
Parts Lists

Developing for older Samsung TVs

If you already have a Samsung TV and want to start developing for it chances are you don’t have the latest and greatest model. But when you install the Tizen development tools they only target 2 operating system versions; the latest version that is out now and the version that is yet to be released in a year or so. Your TV is too old! So what can you do?

If you check the Tizen development forums the suggestion is to install an older version of the development tools. But that’s no fun! And it is possible to develop for the older TVs with the newer tools. Go ahead and install the latest versions of the Tizen development Studio first. While that is installing you will need to download an older version of the Extensions for TV. You can find them at this site. As you scroll through the available versions you will see that if you attempt to get a version older than the 3.0 version you can’t download it. Download the 3.1 or 4.0 extensions. Don’t worry, the  extensions also contain the components needed for TV’s running the 2.3 and 2.4 Tizen version.

tizen extension for tizen sdk

After Tizen Development Studio is installed open the package manager. In the upper right corner of the package manager is a gear icon. Select it.

 

packagemaker

Expand the “Extensions SDK” area of the window to see the extensions installed and click on the + button to add an extension. A window opens asking for a URL. Leave the URL blank and click on the three dots next to it. You’ll now be asked to navigate to a local archive of the extension you with to add. Navigate to the file that you downloaded earlier and select it.  The package manager will take a few moments to install the extension.

When you attempt to create a new project and look at the TV templates available there’s only the 4.0 and 5.0 projects. What gives? The missing project templates can be found under the Custom projects. Select “TV-Samsung v3.0.” Even if you have a TV running Tizen 2.3 this opeion will work. When you click the next button you’ll see the familiar project templates.

Listing Applications on a Tizen Device

In a Tizen project I was working on I found that Tizen Web alone wasn’t enough to help me accomplish my goal. For some of the functionality that I needed a native application would be needed (more on that in another blog post). Rather than completely write the application in native code I was going to use HTML for the UI and a native service for other functionality. This is a Tizen Hybrid application.

The Tizen documentation wasn’t quite clear to me on what identifier to use when trying to launch a service packaged with an HTML application. It mentions using the App ID. This didn’t work for me. I only figured out the right name to use when I tried listing all of the applications and services on the device.

Getting a list of the applications and services is done through tizen.application.getAppsInfo. This function takes as a parameter a callback. The call back is given a list of the applications installed on the device. For my purposes I was only interested in the id member of the objects that were passed back.

  

tizen.application.getAppsInfo(
    function onListInstalledApps(applications) {
        console.log("List of Applications:");
        applications.forEach(
          function(app) {
    		console.log(`  app.id: ${app.id}`);
        });
    });

Once I saw the output of this it was easy to identify the problem I encountered with launching the service.

Screen Shot 2019-05-24 at 10.38.17 AM
Output of app listing code

According to the Tizen documentation when launching a service the ID string used is composed of the package ID and the app ID of the service. The package ID can be found in the confix.xml for the web application.  In the following you can see the package ID is “IVFd9Or08P”.

Screen Shot 2019-05-24 at 4.34.54 PM

The app ID can be found in then tizen-manifest.xml for the service project.

Screen Shot 2019-05-24 at 4.37.53 PM

The app ID here is “org.sample.service.” If you look in the output from the code sample for listing installed applications you will see that the service shows up as IVFd9Or08P.testservice. It is using the entry from the “exec” field instead of the appid field. I’m not sure why the documentation points to the appid only. But I’m happy to have figured out this problem.

 

Raspberry Pi 4 Announced

Raspberry Pi 4
Raspberry Pi 4

The fourth generation of the Raspberry Pi has been announced. Each generation of the Raspberry Pi is primarily identified by its specifications. (Not including the Raspberry Pi Compute module because it generally is not used by hobbyist). With the Raspberry Pi 4, this isn’t the case. There are three variations available. The new Raspberry Pi 4 comes with a 1.5 GHz ARM Cortex-A72 quad-core processor.  With that processor the Raspberry Pi 4 can decode 4K video at 60 FPS or two 4K videos at 30 FPS. The amount of RAM available to the unit depends on the version. The smallest amount of RAM, 1 gig, is available for $35 USD. The next size, 2 gigs, can be purchased for $45 USD. The largest unit, 4 gigs, is $55 USD.

At first glance, the unit will be recognized as a Raspberry PI but a closer look at the ports will show some immediate differences. The Pi has converted from a micro-USB port to USB-C. The full sized HDMI port is gone and has been replaced with two micro-HDMI ports. The unit can drive two displays at once.  A couple of the 4 USB ports have been upgraded to USB 3 while the other two are still USB 2. The wireless capabilities are upgraded to use USB 5.0 and dual-band 802.11ac Wi-Fi.

 

The unit is available for purchase from Raspberry Pi’s site now.  A new case for the Pi 4 and a USB-C power supply of appropriate wattage are both available through the site as well.

 

https://www.raspberrypi.org/products/raspberry-pi-4-model-b/

 

NVIDIA Jetson Development Environment Setup

In previous posts on the NVIDIA Jetson posts I’ve talked about getting the device setup and some additional accessories that you may want to have. The OS image for the NVIDIA Jetson already contains a compiler and other development software. Technically someone can start developing with the OS image as it is when it ships.  But it is not desirable to develop this way.

There may be some things that you prefer to do on your primary computer and you’d like to be able to control the Jetson from your primary machine. The OS image for the Jetson already has SSH enabled. If you are using a Windows machine and net an SSH client I suggest using PuTTY for Windows. It’s a great SSH client and also works as a telnet or serial console when needed. It’s available from https://www.putty.org/.

When Putty is opened by default it is ready to connect to a device over SSH. You only need to enter the IP address to start the connection. Once connected enter your account name and password and you’ll have an active terminal available. For copying files over SSHFTP I use WinSCP (available from https://winscp.net/).

For development on the device I’ve chose Visual Studio Code as my IDE. Yes, it runs on ARMs too.  There are a number of guides available on how to get Visual Studio Code recompiled and installed for an ARMS system. The one that I used is available from code.headmelted.com. In a nutshell I followed two steps; I entered a super user session with the command

su -s

Then I ran the following (which downloads a script from the head melted site and runs it).

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 0CC3FD642696BFC8^C
. <( wget -O - https://code.headmelted.com/installers/apt.sh )

The script only takes a few moments to run. After it’s done you are ready to start development either directly on the board or from another machine.

To make sure that everything works let’s make our first program with the Jetson Nano. This is a “Hello World” program; it is not going to do anything substantial. Let’s also use make to compile the program. make will take care of seeing what needs to be built and issuing the necessary commands. Here it’s use is going to be trivial. But I think starting with simple use of it will give an opportunity for those that are new to it to get oriented with it. Type the following code and save it as helloworld.cu

#include 

__global__ void cuda_hello()
{
    printf("Hello World from GPU!\n");
}

using namespace std;

int main()
{
	cout << "Hello world!" << endl;
	cuda_hello<<>>();
	return 0;
}

We also need to make a new file named makefile. The following couple of lines will say that if there is no file named helloworld (or if the file is out of date based on the date stamp on helloworld.cu) the to compile it using the command /usr/local/cuda/bin/nvcc helloworld.cu -o helloworld

helloworld: helloworld.cu
   usr/local/cuda/bin/nvcc helloworld.cu -o helloworld

Note that there should be a tab on the second line, not a space.
Save this in the same folder as helloworld.cs.

Type make and press enter to build the program. If you type it again nothing will happen. That’s because make sees that the source file hasn’t changed since the executable was build.

Now type ./helloworld and see the program run.

Congratulations, you have a working build environment. Now that we can compile code it’s time to move to something less trivial. In an upcoming post I’ll talk about what CUDA is and how you can use it for calculations with high parallelism.