My Project
spi.h
1 /*************************************************************************\
2 * Copyright (c) 2017 Michael Davidsaver
3 * mrfioc2 is distributed subject to a Software License Agreement found
4 * in file LICENSE that is included with this distribution.
5 \*************************************************************************/
6 #ifndef SPI_H
7 #define SPI_H
8 
9 #include <stdlib.h>
10 
11 #include <string>
12 
13 #include <epicsTypes.h>
14 #include <epicsMutex.h>
15 #include <shareLib.h>
16 
17 namespace mrf {
18 
20 struct epicsShareClass SPIInterface
21 {
22  SPIInterface();
23  virtual ~SPIInterface();
24 
26  virtual void select(unsigned id) =0;
27 
30  virtual epicsUInt8 cycle(epicsUInt8 in) =0;
31 
32  struct Operation {
33  size_t ncycles;
34  const epicsUInt8 *in;
35  epicsUInt8 *out;
36  };
37 
38  virtual void cycles(size_t nops,
39  const Operation *ops);
40 
42  double timeout() const;
43  void setTimeout(double t);
44 
45 protected:
46  mutable epicsMutex mutex;
47 private:
48  double optimo;
49 };
50 
51 class epicsShareClass SPIDevice
52 {
53  SPIInterface * spi;
54  unsigned id;
55 public:
56  SPIDevice() :spi(0), id(0) {}
57  SPIDevice(SPIInterface *spi, unsigned id) :spi(spi), id(id) {}
58 
59  inline SPIInterface* interface() const { return spi; }
60  inline unsigned selector() const { return id; }
61 
62  class Selector {
63  SPIDevice& dev;
64  public:
65  explicit Selector(SPIDevice& dev) :dev(dev)
66  { dev.spi->select(dev.id); }
67  ~Selector()
68  { dev.spi->select(0u); }
69  };
70 
71  static bool lookupDev(const std::string& name, SPIDevice*);
72  static void registerDev(const std::string& name, const SPIDevice& );
73  static void unregisterDev(const std::string& name);
74 };
75 
76 class TimeoutCalculator
77 {
78  const double total;
79  const double factor;
80  const double initial;
81  double accumulated;
82  double next;
83 public:
84  TimeoutCalculator(double total, double factor=2.0, double initial=0.01)
85  :total(total), factor(factor), initial(initial), accumulated(0.0), next(0.0)
86  {}
87  bool ok() const { return accumulated<total; }
88  double inc() {
89  double ret=next;
90  accumulated+=ret;
91  if(next)
92  next*=factor;
93  else
94  next=initial;
95  return ret;
96  }
97  double sofar() const { return accumulated; }
98 };
99 
100 } // namespace mrf
101 
102 #endif // SPI_H
Interface for SPI Master.
Definition: spi.h:21
virtual epicsUInt8 cycle(epicsUInt8 in)=0