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