summaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: 69867513be91e112913c0dcd47e3c36c594b36c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// cpp and linux
#include <chrono>
#include <csignal>
#include <errno.h>
#include <fcntl.h>
#include <iostream>
#include <linux/videodev2.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>

// qt
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QHttpServer>
#include <QImage>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSerialPort>
#include <QTextStream>
#include <QTimer>
#include <QtConcurrent/QtConcurrent>

// orpheus
#include "LibCamera.h"
#include "calibration.h"
#include "camera/veyeimx287m.h"
#include "dumps.h"
#include "imagealgos.h"
#include "profile.h"
#include "protocols/httpserver.h"
#include "scanner.h"

//
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"

extern uint8_t pgm_image[64 + img_width * img_height * sizeof(uint8_t)];
extern size_t pgm_image_size;
extern std::mutex pgm_image_mtx;

#define try_apply_config() \
    if (!applyConfig(config)) { \
        camera->release(); \
        cm->stop(); \
\
        return EXIT_FAILURE; \
    }

ScanningModeFlags scanningModeFlags{ScanningModeFlags::None};

QElapsedTimer calibrationTimer;

extern volatile int32_t positionSteps;

requested_params_t requested_params;

namespace {
Pixels pixels;
std::vector<Pixels> calibrationPixels;
QMutex calibrationPixelsMutex;
} // namespace

using namespace std::chrono_literals;

namespace {
CalibrationTablePtr calibrationTableZ;
CalibrationTablePtr calibrationTableX;
} // namespace

auto printPixels = [](const auto &pixels) {
    for (size_t i = (img_width - 10) / 2;
         i < img_width - ((img_width - 10) / 2);
         ++i) {
        std::cout << pixels[i] << " ";
    }
    std::cout << std::endl;
};

int main(int argc, char *argv[])
{
    auto sigHandler = [](int s) {
        std::cout << "got signal " << s << std::endl;
        std::signal(s, SIG_DFL);
    };

    std::signal(SIGINT, sigHandler);
    std::signal(SIGTERM, sigHandler);

    QCoreApplication app(argc, argv);

    QList<QFuture<void>> initializers;

    qDebug() << "size of raw profile" << sizeof(Pixels);
    if (false) {
        // open binary calibration table
        if (true) {
            initializers << QtConcurrent::run([&]() {
                if (!openCalibrationTable(
                        "/home/user/dumps/binz.calibration_table",
                        // "/tmp/binz.calibration_table",
                        ::calibrationTableZ)) {
                    exit(EXIT_FAILURE);
                }
            });

            initializers << QtConcurrent::run([&]() {
                if (!openCalibrationTable(
                        "/home/user/dumps/binx.calibration_table",
                        // "/tmp/binx.calibration_table",
                        ::calibrationTableX)) {
                    exit(EXIT_FAILURE);
                }
            });
        }

        if (false) {
            auto rawProfiles = openDump("/home/user/dumps/binx");
            qDebug() << "raw x-profiles count is" << rawProfiles.size();
            // qDebug() << "height" << calibrationColumnHeight;

            auto filteredRawProfiles = filter(std::move(rawProfiles));
            qDebug() << "filtered x-profiles count is"
                     << filteredRawProfiles.count();

            ::calibrationTableX = calibrateX(std::move(filteredRawProfiles));

            interpolate(::calibrationTableX);
        }

        // load binary calibration dumps and calibrate
        if (false) {
            if (true) {
                auto rawProfiles = openDump("/home/user/dumps/binz");
                qDebug() << "raw z-profiles count is" << rawProfiles.size();

                auto filteredRawProfiles = filter(std::move(rawProfiles));
                qDebug() << "filtered z-profiles count is"
                         << filteredRawProfiles.count();

                ::calibrationTableZ = calibrateZ(std::move(filteredRawProfiles),
                                                 requested_params.stepsPerMm);

                interpolate(::calibrationTableZ);

                if (!dump(::calibrationTableZ,
                          "/home/user/dumps/binz.calibration_table")) {
                    qApp->exit(EXIT_FAILURE);
                }
            }

            qDebug()
                << "--------------------------------------------------------";

            if (true) {
                auto rawProfiles = openDump("/home/user/dumps/binx");
                qDebug() << "raw x-profiles count is" << rawProfiles.size();

                auto filteredRawProfiles = filter(std::move(rawProfiles));
                qDebug() << "filtered x-profiles count is"
                         << filteredRawProfiles.count();

                ::calibrationTableX = calibrateX(std::move(filteredRawProfiles));

                interpolate(::calibrationTableX);

                if (!dump(::calibrationTableX,
                          "/home/user/dumps/binx.calibration_table")) {
                    qApp->exit(EXIT_FAILURE);
                }
            }
        }
    }

    QElapsedTimer t;
    t.start();

    // FIXME: don't use one var for everything
    int ret;

    auto cameras = VeyeIMX287m::search();

    if (cameras.empty()) {
        std::cerr << "No cameras were identified on the system." << std::endl;

        return EXIT_FAILURE;
    }

    auto camera = cameras.at(0);

    std::cout << "connect everything" << std::endl;

    for (auto &i : initializers)
        i.waitForFinished();
    std::cout << "loaded calibration tables" << std::endl;

    if (!camera->startStream()) {
        return EXIT_FAILURE;
    }

    auto httpServer = std::make_shared<HttpServer>(camera);

    const auto scanner
        = std::make_shared<Scanner>(camera,
                                    std::vector<std::shared_ptr<IProtocol>>{
                                        httpServer});

    QHttpServer qHttpServer;

    qHttpServer.route("/v1/profile", [&]() -> QHttpServerResponse {
        // std::cout << "http: profile" << std::endl;
        return QHttpServerResponse::StatusCode::ServiceUnavailable;
        std::lock_guard<std::mutex> lg(pgm_image_mtx);

        if (!::calibrationTableZ || !::calibrationTableX)
            return QHttpServerResponse::StatusCode::ServiceUnavailable;

        const Profile profile(::pixels,
                              ::calibrationTableZ,
                              ::calibrationTableX);

        const QJsonObject json{{"profile", QJsonObject(profile)}};

        return QHttpServerResponse(QJsonDocument(json).toJson());
    });

    qHttpServer
        .route("/v1/commands/resetEncoder",
               [&](const QHttpServerRequest &request) -> QHttpServerResponse {
                   std::cout << "http: resetEncoder" << std::endl;
                   if (request.method() != QHttpServerRequest::Method::Post) {
                       return QHttpServerResponse::StatusCode::NotFound;
                   }

                   qDebug() << "reset encoder";

                   positionSteps = 0;

                   return QHttpServerResponse::StatusCode::Ok;
               });

    qHttpServer
        .route("/v1/commands/startCalibration",
               [&](const QHttpServerRequest &request) -> QHttpServerResponse {
                   std::cout << "http: startCalibration" << std::endl;
                   if (request.method() != QHttpServerRequest::Method::Post) {
                       return QHttpServerResponse::StatusCode::NotFound;
                   }

                   qDebug() << "start calibration";

                   // TODO: use flags
                   scanningModeFlags = ScanningModeFlags::Calibration;
                   calibrationTimer.start();

                   return QHttpServerResponse::StatusCode::Ok;
               });

    qHttpServer
        .route("/v1/commands/gCode",
               [&](const QHttpServerRequest &request) -> QHttpServerResponse {
                   std::cout << "http: gCode" << std::endl;
                   if (request.method() != QHttpServerRequest::Method::Post) {
                       return QHttpServerResponse::StatusCode::NotFound;
                   }

                   const auto command = request.body();

                   qDebug() << "send gCode:" << command;

                   // printerClient.sendCommand(command);

                   return QHttpServerResponse::StatusCode::Ok;
               });

    qDebug() << "listen: " << qHttpServer.listen(QHostAddress::Any, 8081);

    ////////////////////////////////////////////////////////////////////////////
    std::clog << std::flush;
    std::cerr << std::flush;
    std::cout << "ok for now" << std::endl << std::flush;

    auto result = app.exec();

    return result;
}