Enabling Development Mode on Samsung Tizen TVs

The modern Samsung TVs run the Tizen operating system. You can develop for these just as you might develop for the Tizen based watches. The Tizen TVs are locked down more than the watch is.  To deploy to a Tizen TV you’ll need to both enable developer mode and will have to let the TV know from what address it will be receiving code. If it receives request from other addresses it won’t respond to them.

On the consumer displays there is no obvious way to enable developer mode. The option is hidden. If you open the apps browser (for seeing what other apps there are to install) you can open the developer mode menu by entering “12345” on the remote. A popup window will show from which you can select to turn developer mode “On.” If you are using one of the commercial displays (SSSP, or Samsung Smart Signage Platform) the method to enable developer mode is more obvious. If you open the TV’s menu there is an option called URL Launcher Settings. The developer mode option is within these settings.

On the consumer devices you’ll also be asked to enter the IP address of the machine from which the development will occur. This prevents other rouge devices on your network from doing anything to the TV.  Here you should enter the IP address of your development machine.

After these options are set the TV needs to be rebooted before the changes are fully applied. you can do this by holding the power button on the consumer TVs for two seconds, holding the power off button on a SSSP display for 2 seconds, or removing the power source from the TV and reapplying it.

After the TV boots developer mode is now enabled. However the mode being enabled doesn’t mean that all of the conditions for deploying code have been met. You will need to generate a distributor certificate also. Samsung has this page with instructions for generating a certificate. In following these directions you will need the the Device Unique ID (DUID). To get this you first need to connect to the TV. I prefer to use the sdb utility that comes with the Tizen SDK. It is located in tizen-studio/tools (adjust this path according to the location at which you installed Tizen Studio). The syntax for connecting is:

sdb connect

Sometimes I have to type the command twice before it takes effect. After the connection is successful open the Tizen Device Manager. You should see the TV connection within the UI. If you right-click on the connection you will have the option of selecting the TV’s DUID. Select this option and copy the DUID to the system clipboard. Keep the DUID on the system clipboard and when it is needed during the certificate generation it will automatically be pasted where it is needed.

If you at some point find that you need the TV extensions, don’t have them installed, and don’t see them in the the package manager you can install them using these instructions. https://developer.samsung.com/tv/develop/tools/tv-extension/download/

Creating a certificate based on the Device Uniuque ID (DUID) is slightly different for the two classes of displays. For the consumer displays a Samsung certificate should be created. For the commercial displays a Tizen certificate should be created. It can be a little confusing with Tizen being a Samsung creation. But you may be able to make better sense of it from another perspective. The Samsung certificate is associated with the Samsung App store. The consumer displays access the app store and the certificate rules for that are different than for apps that have no access to the App Store.

samsungremote

samsungtv

Advertisements

Bixby Studio Available for all Bixby Compatible Devices @SDC19

bixby

Samsung announced today at the annual Developer Conference that Bixby Studio, their developer tool for building natural language interactions, is available on all devices that support Bixby. Previously this functionality was only available on the mobile devices. With today’s announcement it is available on other devices such as the TV, Tizen powered refrigerators, and the watch.

To encourage developers to get started with Bixby development they’ve also opened a contest offering thousands of dollars in prizes. For more information on the contest visit BixbyDevJam.com.

Consumer v Commercial Displays

There are two mistakes that one might make about the difference in consumer and commercial displays.

Mistake 1: Commercial Display are just Consumer Displays that cost More

This is an easy mistake to make because at first glance the displays may look alike. But commercial displays are made to withstand a wider range of conditions than their consumer counterparts. An illustration of this that comes to my mine is a display I worked on that was installed in an airport. When the display opened to the public we saw some abuses that we didn’t quite imagine. The installation included touch screens. We expected people to touch the screens. We didn’t expect people to set their children on top of the displays. Yes, this really happened. The displays survived the years that they were at the installation without problems, but I still consider some of what they endured to be borderline abusive. If a small child were set on a consumer display (do not do this) I’m pretty sure that it wouldn’t last long.

That is just one of the tolerances that a commercial display may have that it’s consumer counter part does not. The commercial displays may also have higher tolerance for moisture (perhaps even outdoor use), temperature, potentially higher potentially a brighter screen (as might be needed for outdoor use).

Commercial displays may have a number of features that the consumer counter parts do not.  These may be additional connections (such as RS232), the ability to control several displays at once (as one might want to do in a video array configuration) and even internal media players or security features.

Mistake 2: A Commercial Display would make a good Home Display

This misconception comes from the idea that a commercial display is a consumer display with features added. The reality is that while the commercial displays may have additional features they might also be missing features that the consumer displays have. If you buy a typical consumer display above a certain size it will have the ability to run several consumer oriented applications such as a Netflix and Hulu player and a few others. The commercial displays don’t have this; and that is understandable since they are not for engaging in these consumer activities. A person that pays the extra money to get a commercial display may leave one feeling quite disappointed after realizing the features that are not available.

Samsung Consumer Displays v Samsung Commercial Displays

I’m looking at to displays that were made at about the same time. Both are made by Samsung; one is a consumer display and the other is a commercial display. Getting the differences between them has required my own exploration and experimentation. Samsung has a site at https://samsungDforum.com that contains information about the consumer displays. Unfortunately this information is only available to those that sign up for the Samsung Partner program. From what I’ve read about this program an NDA is required to enroll within it. I have not signed up for this program; if I did then I wouldn’t be able to talk about the information gained within it. As part of my interest in the displays is to talk about them (on this blog) I’m instead am gathering information both from experimenting with the display and through scraps of information available on the Internet.

The process of experimentation has had it’s moments of frustration, and I’ve already written some material on my experiences that are to be posted in the future.  In my next post on this topic I’ll talk about the differences in the Samsung Consumer and Commercial displays.

 

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.