blob: cbe9282d7b38e9d9fb2d969c5f096ffdc7da45c7 [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
Vernon Mauerydcff1502022-09-28 11:12:46 -070051 void spiReadData(uint32_t startAddr, size_t dataLen, void* dataRes)
Rajashekar Gade Reddyc8864062019-10-15 16:52:30 +053052 {
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
Vernon Mauerydcff1502022-09-28 11:12:46 -070060 if (read(fd, dataRes, dataLen) != static_cast<ssize_t>(dataLen))
Rajashekar Gade Reddyc8864062019-10-15 16:52:30 +053061 {
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};