How to quickly develop an IOT app control smart light (IOS version) based on SDK

Time:2021-4-30

Background:

With the continuous progress of science and technology, more and more smart home products and services come into people’s daily life. Smart light is a common intelligent device. After installing the smart light, users can easily adjust the indoor color and brightness by using the mobile app, and set different lighting scenes to easily create a warm, relaxed, interesting or inspiring indoor space.

For Android version, please refer to:How to quickly develop an IOT app control smart bulb (Android version) based on SDK

Introduction of RGB 5-way intelligent lamp

Including functions:

How to quickly develop an IOT app control smart light (IOS version) based on SDK

There are white light and color light in five way lights, which can be switched between two modes and cannot be enabled at the same time.

RGB color model

RGB (red, green, blue) color mode is a kind of hardware oriented color model. The display system uses RGB color model for image display. RGB color model belongs to the principle of additive color mixing. The higher the value of each primary color, the brighter the color. When RGB is 0, it is black, and when RGB is 255, it is white.

RGB color model is direct, but there is no direct relationship between RGB value and the three attributes of color, which cannot reveal the relationship between colors.

HSV color model

HSV color model is a kind of color model oriented to user’s senses, which focuses on color representation. This is a color model based on the physiological characteristic that human visual system is more sensitive to brightness than color value. It is closer to people’s perception of color than RGB. Very intuitive expression of color tone, bright degree and shade degree, convenient for color contrast.

HSV (hue, saturation and value) correspond to hue, saturation and lightness respectively.

  • Hue H: measured by angle, the value range is 0 °~ three hundred and sixty °, Starting from red, counter clockwise, red is 0 °, Green is 120 °, Blue is 240 °, Yellow is 60 °, Blue is 180 °, Magenta is 300 °, The angle corresponding to the central axis of the cylinder.
  • Saturation S: the purity of the color, corresponding to the distance from the central axis of the cylinder. The higher the value is, the darker the color is. The lower the value is, the grayer the color is. The value range is 0.0 ~ 1.0, s = 0 for white.
  • Lightness V: indicates the brightness of the color. The value range is 0.0 (black) to 1.0 (white). Corresponding to the height around the central axis of the cylinder, the axis value is from black v = 0 at the bottom to white v = 1 at the top.

How to quickly develop an IOT app control smart light (IOS version) based on SDK

Basic preparation

When developing a smart light app based on SDK, you need to make the following preparations:

  • Create app SDK
  • Integrated SDK
  • Registration and login
  • Creating a family
  • Equipment distribution network
  • Equipment control

Specific reference

Function point introduction

Function point is the abstract representation of product function and the abstraction of specific intelligent device function, which is used to describe product function and its parameters.

  • Function point ID: coding of function point. The function data between the device and the cloud is transmitted through the function point ID.
  • Function point name: custom function name.
  • Identification name: function point code value, used for multi language management of APP display function name. Supports letters, numbers and underscores, starting with letters.
  • data type

How to quickly develop an IOT app control smart light (IOS version) based on SDK

Data transmission type

  • Can be issued can be reported: command data can be sent to the device, device data can be transmitted to the cloud.
  • Report only: data can only be transferred from the device to the cloud.
  • Distribution only: data can only be sent from the cloud to the device.

The function points of product PID: “ylr9r01cmwnmrqeb” are shown in the figure below:

How to quickly develop an IOT app control smart light (IOS version) based on SDK

Introduction to demo

Demo address

Demo address:https://github.com/tuya/tuya-home-ios-sdkFunction branch: Main

SDK document address:https://tuyainc.github.io/tuyasmart_home_ios_sdk_doc/zh-hans/

Demo download

In the command line of the terminal, enter:

git clone https:_//github.com/tuya/tuya-home-ios-sdk.git_

Download the demo locally.

Environment configuration

1. Open project settings, target = > general, modifyBundle IdentifierThe IOS package name corresponding to the graffiti developer platform

2. Import the security image to the project root directory and rename it tot_s.bmpAnd add it to “project settings = > target = > build phases = > copy bundle resources”.

3. At the end of the projectPrefixHeader.pchAdd the following to the file:

#import <TuyaSmartHomeKit/TuyaSmartKit.h>

4. OpenAppDelegate.mFile, in[AppDelegate application:didFinishLaunchingWithOptions:]Method to initialize the SDK:

[[TuyaSmartSDK sharedInstance] startWithAppKey:<#your_app_key#> secretKey:<#your_secret_key#>];

5. Open debug mode

In the process of development, you can open debug mode and print some logs to analyze problems.

Objc:

#ifdef DEBUG
    [[TuyaSmartSDK sharedInstance] setDebugMode:YES];
#else
#endif

Demo content

We can refer to the demo code in the development process.

In the demo, we have completed the switch, brightness, heating and cooling, color control of intelligent light bulb based on DP point control.

The intelligent light control page is shown in the following figure:

How to quickly develop an IOT app control smart light (IOS version) based on SDK

Function point ID

NSString * const kLightSwtichDpId = @"1";/*  DP point of control light switch*/
NSString * const kLightColorTypeDpId = @"2";/*  DP point of control lamp type*/

NSString * const kLightColorBrightDpId = @"3";/*  DP point for controlling the brightness of color lights*/
NSString * const kLightColorTempDpId = @"4";/*  Control the DP point of color lamp temp*/

NSString * const kLightColorDpId = @"5";/*  DP point of controlling lamp color*/

Switch operation

- (void)switchAction:(UISwitch *)sender {
    //Switch operation
    WEAKSELF_AT
    [TPDemoProgressUtils showMessag:TYSDKDemoLocalizedString(@"loading", @"") toView:self.view];
    
    [self.device publishDps:@{kLightSwtichDpId:@(sender.isOn)} success:^{
        [TPDemoProgressUtils hideHUDForView:weakSelf_AT.view animated:NO];
    } failure:^(NSError *error) {
        [TPDemoProgressUtils hideHUDForView:weakSelf_AT.view animated:NO];
        [TPDemoProgressUtils showError:error.localizedDescription];
    }];
}

Brightness adjustment (both in white and color mode)

There are two cases: in white light mode and color light mode

// Bright
NSDictionary *dps = self.device.deviceModel.dps;
if ([[dps objectForKey:kLightColorTypeDpId] isEqualToString:@"colour"]) {
    int ir,ig,ib;

    _hsvValue.v = value;

    HSVToRGB(_hsvValue.h, _hsvValue.s, _hsvValue.v, &ir, &ig, &ib);

    UIColor *resColor = RGBCOLOR(ir, ig, ib);

    NSString *dpsString = [NSString stringWithFormat:@"%@%@",
                           [[[resColor hexStringFromColor] lowercaseString] substringFromIndex:1],
                           [self getHexStringFromHSV:_hsvValue]];

    publishDps = @{
                     kLightSwtichDpId:@(YES),
                     kLightColorDpId:dpsString,
                     kLightColorTypeDpId:@"colour"
                     };

} else {
    CGFloat tempV = (value * 100 - 1)/(100.0-1.0) * (self.maxValue - self.minValue) + self.minValue;
    int val = [self round:tempV];
    publishDps = @{
                  kLightSwtichDpId:@(YES),
                  kLightColorBrightDpId:@(val),
                  kLightColorTypeDpId:@"white",
                  };
}

[self.device publishDps:publishDps success:^{
        
} failure:^(NSError *error) {

}];

Cooling and heating adjustment (only supported by white light mode)

// Temperature
int dpsInt = (int)(value * (self.tempMaxValue - self.tempMinValue) + self.tempMinValue);
publishDps = @{
    kLightColorTypeDpId:@"white",
    kLightColorTempDpId:@(dpsInt)
};

[self.device publishDps:publishDps success:^{
        
} failure:^(NSError *error) {

}];

Color adjustment (only supported by color light mode)

#pragma mark - RSColorPickerViewDelegate
- (void)colorPickerDidChangeSelection:(RSColorPickerView *)colorPicker {

    NSDictionary *dps = self.device.deviceModel.dps;
    
    BOOL isSwitch = [[dps objectForKey:kLightSwtichDpId] tysdk_toBool];
    
    if (!isSwitch) {
        return;
    }

    HSVType hsv = [self.class getHSVFromUIColor:colorPicker.selectionColor];
    
    _hsvValue.h = hsv.h;
    _hsvValue.s = hsv.s;
    _currentH = hsv.h;
    
    if (_hsvValue.v == 0) {
        _hsvValue.v = 1;
    }

    int r, g, b;
    
    HSVToRGB(_hsvValue.h, _hsvValue.s, _hsvValue.v, &r, &g, &b);
    
    NSString *dpsString = [NSString stringWithFormat:@"%02x%02x%02x%@",
                           (unsigned int)r,
                           (unsigned int)g,
                           (unsigned int)b,
                           [self getHexStringFromHSV:_hsvValue]];
    
    NSDictionary *publishDps = @{
                                 kLightColorDpId:dpsString,
                                 kLightColorTypeDpId:@"colour",
                                 };

    [self.device publishDps:publishDps success:^{
            
    } failure:^(NSError *error) {
        
    }];
}

Saturation adjustment (only supported by color light mode)

// Saturation
_hsvValue.s = value;

if (_hsvValue.v == 0) {
    _hsvValue.v = 1;
}
int r, g, b;
HSVToRGB(_hsvValue.h, _hsvValue.s, _hsvValue.v, &r, &g, &b);

NSString *dpsString = [NSString stringWithFormat:@"%02x%02x%02x%@",
                       (unsigned int)r,
                       (unsigned int)g,
                       (unsigned int)b,
                       [self getHexStringFromHSV:_hsvValue]];

publishDps = @{
                 kLightColorDpId:dpsString,
                 kLightColorTypeDpId:@"colour",
             };
[self.device publishDps:publishDps success:^{
        
} failure:^(NSError *error) {

}];

Smart light status change callback refresh

#pragma mark - TuyaSmartDeviceDelegate

///DP data update
- (void)device:(TuyaSmartDevice *)device dpsUpdate:(NSDictionary *)dps {
    [self reloadData];
}

- (void)reloadData {
    
    _hsvValue = [self getHSVFromDpId:kLightColorDpId];
    
    NSDictionary *dps = self.device.deviceModel.dps;
    BOOL isSwitch = [[dps objectForKey:kLightSwtichDpId] boolValue];
    [self.switchButton setOn:isSwitch];
    
    double brightnessValue = [self getBrightness:dps];
    [self.brightSliderView setSliderValue:brightnessValue];
    
    double tempValue = [self getTempValue:[[dps objectForKey:kLightColorTempDpId] doubleValue]];
    [self.tempSliderView setSliderValue:tempValue];
    
    HSVType hsv = [self getHSVFromDpId:kLightColorDpId];
    UIColor *color = [self getColorFromDpId:kLightColorDpId];
    
    NSLog(@" h : %f, s : %f, v : %f, color : %@", hsv.h, hsv.s, hsv.v, color);
    if (fabs(roundf(hsv.h) - roundf(_currentH)) > 1) {

        _currentH = hsv.h;
        
        self.colorPicker.selectionColor = color;
        self.colorPicker.brightness = 1;
        self.colorPicker.opaque = YES;
    }
    
    [self.saturationSliderView setSliderValue:hsv.s];
}

Recommended Today

King glory: app interface of E-sports data [player information]

King glory E-sports API dedicated data interface sharing code Example demonstration: kingglory [player information] interfaceShare and use wild sub datahttp://yes-esports.com/Sample code of data interface call of E-sports API The details are as follows:import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.annotation.JSONField; import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Paths;import java.util.List; /**@API: score [email protected]: https://www.xxe.io/@Website: http://www.yesesport.com/@Website: http://www.yezidianjing.com/*/public class CsgoMatch { public static void main(String[] args) {try […]