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