blob: 0ebe6e520bbd5c7d4a05fc3e8f85d7cd9915b41f [file] [log] [blame]
Rajashekar Gade Reddyc8864062019-10-15 16:52:30 +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#include <experimental/filesystem>
19
20class 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
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
43 virtual ~SPIDev()
44 {
45 if (!(fd < 0))
46 {
47 close(fd);
48 }
49 }
50
51 void spiReadData(const uint32_t startAddr, const size_t dataLen,
52 void* dataRes)
53 {
54 if (lseek(fd, startAddr, SEEK_SET) < 0)
55 {
56 std::string msg = "Failed to do lseek on mtd device. errno=" +
57 std::string(std::strerror(errno));
58 throw std::runtime_error(msg);
59 }
60
61 if (read(fd, dataRes, dataLen) != dataLen)
62 {
63 std::string msg = "Failed to read on mtd device. errno=" +
64 std::string(std::strerror(errno));
65 throw std::runtime_error(msg);
66 }
67
68 return;
69 }
70};