blob: 667318aadc18cb77f365594e611d371b75aee854 [file] [log] [blame]
AppaRao Puli4b639a22019-10-01 18:12:59 +05301/*
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
19#include <stdio.h>
AppaRao Puli67d184c2020-05-29 00:48:33 +053020
AppaRao Puli4b639a22019-10-01 18:12:59 +053021#include <cstring>
22#include <experimental/filesystem>
23
24namespace intel
25{
26namespace pfr
27{
28
29/** @class SPIDev
30 * @brief Responsible for handling file pointer
31 */
32class SPIDev
33{
34 private:
35 /** @brief handler for operating on file */
36 int fd = -1;
37
38 public:
39 SPIDev() = delete;
40 SPIDev(const SPIDev&) = delete;
41 SPIDev& operator=(const SPIDev&) = delete;
42 SPIDev(SPIDev&&) = delete;
43 SPIDev& operator=(SPIDev&&) = delete;
44
45 /** @brief Opens spi(mtd) device file
46 *
47 * @param[in] devNo - MTD device number
48 */
49 SPIDev(const std::string& spiDev) :
50 fd(open(spiDev.c_str(), O_RDWR | O_CLOEXEC))
51 {
52 if (fd < 0)
53 {
54 std::string msg = "Unable to open mtd device. errno=" +
55 std::string(std::strerror(errno));
56 throw std::runtime_error(msg);
57 }
58 }
59
60 /** @brief Reads the byte data from SPI(MTD) device
61 *
62 * @param[in] startAddr - start address
63 * @param[in] dataLen - No of byte to read
64 * @param[out] dataRes - Out data pointer
65 */
66 void spiReadData(const uint32_t startAddr, const size_t dataLen,
67 void* dataRes)
68 {
69 if (lseek(fd, startAddr, SEEK_SET) < 0)
70 {
71 std::string msg = "Failed to do lseek on mtd device. errno=" +
72 std::string(std::strerror(errno));
73 throw std::runtime_error(msg);
74 }
75
76 if (read(fd, dataRes, dataLen) != dataLen)
77 {
78 std::string msg = "Failed to read on mtd device. errno=" +
79 std::string(std::strerror(errno));
80 throw std::runtime_error(msg);
81 }
82
83 return;
84 }
85
86 virtual ~SPIDev()
87 {
88 if (!(fd < 0))
89 {
90 close(fd);
91 }
92 }
93};
94
95} // namespace pfr
96} // namespace intel