Merge branch 'smart-blind'
[apps/native/st-things-blind.git] / src / resource_illuminance_sensor.c
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd.
3  *
4  * Contact: Jin Yoon <jinny.yoon@samsung.com>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an AS IS BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <peripheral_io.h>
22 #include <sys/time.h>
23
24 #include "log.h"
25
26 #define I2C_PIN_MAX 28
27 /* I2C */
28 #define GY30_ADDR 0x23 /* Address of GY30 light sensor */
29 #define GY30_CONT_HIGH_RES_MODE 0x10 /* Start measurement at 11x resolution. Measurement time is approx 120mx */
30 #define GY30_CONSTANT_NUM (1.2)
31
32 static struct {
33         int opened;
34         peripheral_i2c_h sensor_h;
35 } resource_sensor_s;
36
37 void resource_close_illuminance_sensor(void)
38 {
39         if (!resource_sensor_s.opened)
40                 return;
41
42         _I("Illuminance Sensor is finishing...");
43         peripheral_i2c_close(resource_sensor_s.sensor_h);
44         resource_sensor_s.opened = 0;
45 }
46
47 int resource_read_illuminance_sensor(int i2c_bus, uint32_t *out_value)
48 {
49         int ret = PERIPHERAL_ERROR_NONE;
50         static int write = 0;
51         unsigned char buf[10] = { 0, };
52
53         if (!resource_sensor_s.opened) {
54                 ret = peripheral_i2c_open(i2c_bus, GY30_ADDR, &resource_sensor_s.sensor_h);
55                 if (ret != PERIPHERAL_ERROR_NONE) {
56                         _E("i2c open error : %s", get_error_message(ret));
57                         return -1;
58                 }
59                 resource_sensor_s.opened = 1;
60                 write = 0;
61         }
62
63         buf[0] = 0x10;
64
65         if (!write) {
66                 ret = peripheral_i2c_write(resource_sensor_s.sensor_h, buf, 1);
67                 if (ret != PERIPHERAL_ERROR_NONE) {
68                         _E("i2c write error : %s", get_error_message(ret));
69                         return -1;
70                 }
71                 write = 1;
72         }
73
74         ret = peripheral_i2c_read(resource_sensor_s.sensor_h, buf, 2);
75         if (ret != PERIPHERAL_ERROR_NONE) {
76                 _E("i2c read error : %s", get_error_message(ret));
77                 return -1;
78         }
79
80         *out_value = (buf[0] << 8 | buf[1]) / GY30_CONSTANT_NUM; // Just Sum High 8bit and Low 8bit
81
82         return 0;
83 }