1 /*
2 // Copyright (c) 2018 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 
17 #include "power_button.hpp"
18 
19 // add the button iface class to registry
20 static ButtonIFRegister<PowerButton> buttonRegister;
21 
22 void PowerButton::simPress()
23 {
24     pressed();
25 }
26 
27 void PowerButton::simLongPress()
28 {
29     pressedLong();
30 }
31 
32 void PowerButton::updatePressedTime()
33 {
34     pressedTime = std::chrono::steady_clock::now();
35 }
36 
37 auto PowerButton::getPressTime() const
38 {
39     return pressedTime;
40 }
41 
42 void PowerButton::handleEvent(sd_event_source* es, int fd, uint32_t revents)
43 {
44     int n = -1;
45     char buf = '0';
46 
47     n = ::lseek(fd, 0, SEEK_SET);
48 
49     if (n < 0)
50     {
51         phosphor::logging::log<phosphor::logging::level::ERR>(
52             "POWER_BUTTON: lseek error!");
53         return;
54     }
55 
56     n = ::read(fd, &buf, sizeof(buf));
57     if (n < 0)
58     {
59         phosphor::logging::log<phosphor::logging::level::ERR>(
60             "POWER_BUTTON: read error!");
61         return;
62     }
63 
64     if (buf == '0')
65     {
66         phosphor::logging::log<phosphor::logging::level::DEBUG>(
67             "POWER_BUTTON: pressed");
68 
69         updatePressedTime();
70         // emit pressed signal
71         pressed();
72     }
73     else
74     {
75         phosphor::logging::log<phosphor::logging::level::DEBUG>(
76             "POWER_BUTTON: released");
77 
78         auto now = std::chrono::steady_clock::now();
79         auto d = std::chrono::duration_cast<std::chrono::milliseconds>(
80             now - getPressTime());
81 
82         if (d > std::chrono::milliseconds(LONG_PRESS_TIME_MS))
83         {
84             pressedLong();
85         }
86         else
87         {
88             // released
89             released();
90         }
91     }
92 }
93