xref: /openbmc/intel-ipmi-oem/include/spiDev.hpp (revision dcff1506)
1 /*
2 // Copyright (c) 2019 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 #pragma once
18 #include <experimental/filesystem>
19 
20 class SPIDev
21 {
22   private:
23     int fd = -1;
24 
25   public:
26     SPIDev() = delete;
27     SPIDev(const SPIDev&) = delete;
28     SPIDev& operator=(const SPIDev&) = delete;
29     SPIDev(SPIDev&&) = delete;
30     SPIDev& operator=(SPIDev&&) = delete;
31 
SPIDev(const std::string & spiDev)32     SPIDev(const std::string& spiDev) :
33         fd(open(spiDev.c_str(), O_RDWR | O_CLOEXEC))
34     {
35         if (fd < 0)
36         {
37             std::string msg = "Unable to open mtd device. errno=" +
38                               std::string(std::strerror(errno));
39             throw std::runtime_error(msg);
40         }
41     }
42 
~SPIDev()43     virtual ~SPIDev()
44     {
45         if (!(fd < 0))
46         {
47             close(fd);
48         }
49     }
50 
spiReadData(uint32_t startAddr,size_t dataLen,void * dataRes)51     void spiReadData(uint32_t startAddr, size_t dataLen, void* dataRes)
52     {
53         if (lseek(fd, startAddr, SEEK_SET) < 0)
54         {
55             std::string msg = "Failed to do lseek on mtd device. errno=" +
56                               std::string(std::strerror(errno));
57             throw std::runtime_error(msg);
58         }
59 
60         if (read(fd, dataRes, dataLen) != static_cast<ssize_t>(dataLen))
61         {
62             std::string msg = "Failed to read on mtd device. errno=" +
63                               std::string(std::strerror(errno));
64             throw std::runtime_error(msg);
65         }
66 
67         return;
68     }
69 };
70