chenluhua1980
2025-11-14 050d4ab486dbec6f183bd27882c79048e4c687bd
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#include "stdafx.h"
#include "GlassJson.h"
 
#include <chrono>
#include <optional>
#include <sstream>
#include <limits>
#include <cstdlib>
 
#include "CGlass.h"
#include "CParam.h"
#include "CJobDataS.h"
#include "CPath.h"
 
using namespace SERVO;
 
// ==================== Ð¡¹¤¾ß£¨¼æÈÝÀÏ JsonCpp£© ====================
 
// ½« optional<time_point> ×ªºÁÃ루int64£©£¬ÔÙÒÔ×Ö·û´®Ð´Èë JSON
static std::string tp_to_ms_str(std::optional<std::chrono::system_clock::time_point> tp) {
    if (!tp) return std::string(); // ¿Õ´®±íʾÎÞ
    using namespace std::chrono;
    long long ms = duration_cast<milliseconds>(tp->time_since_epoch()).count();
    return std::to_string(ms);
}
 
// ´Ó JSON µÄ×Ö·û´®/Êý×ÖÈÝÈÌʽ¶ÁÈ¡ 64 Î»£¬ÓÅÏÈ string
static bool get_ll_from_json(const Json::Value& v, const char* key, long long& out) {
    if (!v.isMember(key)) return false;
    const Json::Value& x = v[key];
    if (x.isString()) {
        const std::string s = x.asString();
        if (s.empty()) return false;
        char* endp = nullptr;
        errno = 0;
#if defined(_MSC_VER)
        long long val = _strtoi64(s.c_str(), &endp, 10);
#else
        long long val = std::strtoll(s.c_str(), &endp, 10);
#endif
        if (endp && *endp == '\0' && errno == 0) { out = val; return true; }
        // ÈÝ´í£ºÈç¹ûÆäʵÊÇÊý×Ö×Ö·û´®£¨´ø¿Õ¸ñ£©£¬ÔÙÊÔÒ»´Î
        try { out = std::stoll(s); return true; }
        catch (...) {}
        return false;
    }
    if (x.isInt()) { out = static_cast<long long>(x.asInt());  return true; }
    if (x.isUInt()) { out = static_cast<long long>(x.asUInt()); return true; }
    if (x.isDouble()) { out = static_cast<long long>(x.asDouble()); return true; }
    return false;
}
 
// Ð´ 64 Î»Îª×Ö·û´®£¨¿ç°æ±¾/¿çÓïÑÔ¸üÎÈ£©
static void put_ull_as_str(Json::Value& obj, const char* key, unsigned long long v) {
    obj[key] = Json::Value(std::to_string(v));
}
static void put_ll_as_str(Json::Value& obj, const char* key, long long v) {
    obj[key] = Json::Value(std::to_string(v));
}
 
// ¼ò»¯¶ÁÈ¡£¨´øÄ¬ÈÏ£©
static int         JInt(const Json::Value& v, const char* k, int d = 0)
{
    return v.isMember(k) ? v[k].asInt() : d;
}
static unsigned    JUInt(const Json::Value& v, const char* k, unsigned d = 0)
{
    return v.isMember(k) ? v[k].asUInt() : d;
}
static bool        JBool(const Json::Value& v, const char* k, bool d = false)
{
    return v.isMember(k) ? v[k].asBool() : d;
}
static std::string JStr(const Json::Value& v, const char* k, const std::string& d = "")
{
    return v.isMember(k) ? v[k].asString() : d;
}
static double      JDouble(const Json::Value& v, const char* k, double d = 0.0)
{
    return v.isMember(k) ? v[k].asDouble() : d;
}
 
// ==================== CGlass -> JSON ====================
 
Json::Value GlassJson::ToJson(const CGlass& gConst) {
    CGlass& g = const_cast<CGlass&>(gConst); // Ðí¶à getter ²»ÊÇ const
    Json::Value root(Json::objectValue);
 
    // »ù±¾
    root["id"] = g.getID();
    root["materials"] = static_cast<int>(g.getType());              // 0/1/2/3
    root["buddy_id"] = g.getBuddyId();
    root["has_buddy"] = (g.getBuddy() != nullptr);
 
    int port = 0, slot = 0;
    g.getOrginPort(port, slot);
    root["origin_port"] = port;
    root["origin_slot"] = slot;
 
    root["scheduled"] = g.isScheduledForProcessing() ? true : false;
    root["state"] = static_cast<int>(g.state());                // GlsState -> int
    root["fail_reason"] = g.m_failReason;
 
    // Ê±¼ä´Á£ºÒÔ×Ö·û´®Ð´
    root["t_queued_ms"] = tp_to_ms_str(g.tQueued());
    root["t_start_ms"] = tp_to_ms_str(g.tStart());
    root["t_end_ms"] = tp_to_ms_str(g.tEnd());
 
    // params: vector<CParam>
    {
        Json::Value arr(Json::arrayValue);
        for (auto& p : g.getParams()) {
            Json::Value jp(Json::objectValue);
            jp["id"] = p.getId();
            jp["name"] = p.getName();
            jp["unit"] = p.getUnit();
            int vt = p.getValueType(); // PVT_INT=0, PVT_DOUBLE=1
            jp["vtype"] = vt;
            if (vt == PVT_INT)  jp["iv"] = p.getIntValue();
            else                jp["fv"] = p.getDoubleValue();
            arr.append(std::move(jp));
        }
        root["params"] = std::move(arr);
    }
 
    // JobDataS
    {
        CJobDataS& s = *g.getJobDataS();
        Json::Value js(Json::objectValue);
        js["cassette_seq_no"] = s.getCassetteSequenceNo();
        js["job_seq_no"] = s.getJobSequenceNo();
        js["lot_id"] = s.getLotId();
        js["product_id"] = s.getProductId();
        js["operation_id"] = s.getOperationId();
        js["glass1_id"] = s.getGlass1Id();
        js["glass2_id"] = s.getGlass2Id();
 
        js["job_type"] = s.getJobType();
        js["materials_type"] = s.getMaterialsType();
        js["product_type"] = s.getProductType();
        js["dummy_type"] = s.getDummyType();
        js["skip_flag"] = s.getSkipFlag();
        js["process_flag"] = s.getProcessFlag();
        js["process_reason"] = s.getProcessResonCode();
        js["last_glass_flag"] = s.getLastGlassFlag();
        js["first_glass_flag"] = s.getFirstGlassFlag();
 
        Json::Value q(Json::arrayValue);
        for (int i = 0; i < 3; i++) q.append(s.getQTime(i));
        js["qtime"] = std::move(q);
        js["qtime_over_flag"] = s.getQTimeOverFlag();
 
        js["master_recipe"] = s.getMasterRecipe();
        Json::Value rids(Json::arrayValue);
        for (int i = 0; i < DEVICE_COUNT; i++) rids.append(s.getDeviceRecipeId(i));
        js["device_recipe_ids"] = std::move(rids);
 
        js["panel_measure"] = s.getPanelMeasure();
        js["mode"] = s.getMode();
        js["slot_unit_select_flag"] = s.getSlotUnitSelectFlag();
 
        js["source_port_no"] = s.getSourcePortNo();
        js["source_slot_no"] = s.getSourceSlotNo();
        js["target_port_no"] = s.getTargetPortNo();
        js["target_slot_no"] = s.getTargetSlotNo();
 
        js["product_judge"] = s.getProductJudge();
 
        root["job_data_s"] = std::move(js);
    }
 
    // path£¨Á´±í ¡ú Êý×飻ʱ¼ä×Ö¶ÎÒÔ×Ö·û´®´æ£©
    {
        Json::Value arr(Json::arrayValue);
        if (auto head = g.getPath()) {
            CPath* p = head->getHeadPath();
            while (p) {
                Json::Value n(Json::objectValue);
                n["eq_id"] = p->getEqID();
                n["unit"] = p->getUnit();
                n["slot"] = p->getUnit();
                put_ull_as_str(n, "time_in", static_cast<unsigned long long>(p->getInTime()));
                put_ull_as_str(n, "time_out", static_cast<unsigned long long>(p->getOutTime()));
                n["processed"] = p->isProcessEnd() ? true : false;
                n["insp_result"] = static_cast<int>(p->getInspResult()); // 0:not,1:pass,2:fail
                arr.append(std::move(n));
                p = p->getNext();
            }
        }
        root["path"] = std::move(arr);
    }
 
    // SVÊý¾Ý£ºÈý²ã½á¹¹ÐòÁл¯
    {
        Json::Value svDataObj(Json::objectValue);
        const auto& allSVData = g.getAllSVData();
 
        for (const auto& machinePair : allSVData) {
            int machineId = machinePair.first;
            const auto& dataTypes = machinePair.second;
 
            Json::Value machineObj(Json::objectValue);
            for (const auto& dataTypePair : dataTypes) {
                const std::string& dataType = dataTypePair.first;
                const auto& dataItems = dataTypePair.second;
 
                Json::Value dataArray(Json::arrayValue);
                for (const auto& item : dataItems) {
                    Json::Value itemObj(Json::objectValue);
                    // Ê±¼ä´Áת»»ÎªºÁÃë×Ö·û´®
                    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                        item.timestamp.time_since_epoch()).count();
                    itemObj["t"] = std::to_string(ms);
                    itemObj["v"] = item.value;
                    dataArray.append(itemObj);
                }
                machineObj[dataType] = dataArray;
            }
            svDataObj[std::to_string(machineId)] = machineObj;
        }
        root["sv_datas"] = svDataObj;
    }
 
    root["payload_version"] = 2; // °æ±¾Éý¼¶£¬ÒòΪÐÂÔöÁËsv_datas×Ö¶Î
    return root;
}
 
// ==================== JSON -> CGlass ====================
 
void GlassJson::FromJson(const Json::Value& root, CGlass& g) {
    // »ù±¾
    g.setID(JStr(root, "id").c_str());
    g.setType(static_cast<MaterialsType>(JInt(root, "materials", 0)));
    g.setBuddyId(JStr(root, "buddy_id"));
    g.setScheduledForProcessing(JBool(root, "scheduled") ? TRUE : FALSE);
    g.m_failReason = JStr(root, "fail_reason");
    g.setOriginPort(JInt(root, "origin_port", 0), JInt(root, "origin_slot", 0));
 
    // ×´Ì¬Óëʱ¼ä£¨Ê±¼ä´Ó×Ö·û´®/Êý×ÖÈÝ´í½âÎö£©
    g.m_state = static_cast<GlsState>(JInt(root, "state", 0));
    long long ms = 0;
    if (get_ll_from_json(root, "t_queued_ms", ms)) g.m_tQueued = std::chrono::system_clock::time_point(std::chrono::milliseconds(ms)); else g.m_tQueued = std::nullopt;
    if (get_ll_from_json(root, "t_start_ms", ms)) g.m_tStart = std::chrono::system_clock::time_point(std::chrono::milliseconds(ms)); else g.m_tStart = std::nullopt;
    if (get_ll_from_json(root, "t_end_ms", ms)) g.m_tEnd = std::chrono::system_clock::time_point(std::chrono::milliseconds(ms)); else g.m_tEnd = std::nullopt;
 
    // params
    g.getParams().clear();
    if (root.isMember("params") && root["params"].isArray()) {
        for (const auto& jp : root["params"]) {
            const int vt = JInt(jp, "vtype", 0); // 0=int,1=double
            const std::string name = JStr(jp, "name");
            const std::string id = JStr(jp, "id");
            const std::string unit = JStr(jp, "unit");
            if (vt == PVT_INT) {
                CParam p(name.c_str(), id.c_str(), unit.c_str(), JInt(jp, "iv", 0));
                g.getParams().push_back(std::move(p));
            }
            else {
                CParam p(name.c_str(), id.c_str(), unit.c_str(), JDouble(jp, "fv", 0.0));
                g.getParams().push_back(std::move(p));
            }
        }
    }
 
    // JobDataS
    if (root.isMember("job_data_s") && root["job_data_s"].isObject()) {
        const auto& js = root["job_data_s"];
        CJobDataS* s = g.getJobDataS();
 
        s->setCassetteSequenceNo(JInt(js, "cassette_seq_no", 0));
        s->setJobSequenceNo(JInt(js, "job_seq_no", 0));
 
        s->setLotId(JStr(js, "lot_id").c_str());
        s->setProductId(JStr(js, "product_id").c_str());
        s->setOperationId(JStr(js, "operation_id").c_str());
        s->setGlass1Id(JStr(js, "glass1_id").c_str());
        s->setGlass2Id(JStr(js, "glass2_id").c_str());
 
        s->setJobType(JInt(js, "job_type", 0));
        s->setMaterialsType(JInt(js, "materials_type", 0));
        s->setProductType(JInt(js, "product_type", 0));
        s->setDummyType(JInt(js, "dummy_type", 0));
        s->setSkipFlag(JInt(js, "skip_flag", 0));
        s->setProcessFlag(JInt(js, "process_flag", 0));
        s->setProcessResonCode(JInt(js, "process_reason", 0));
        s->setLastGlassFlag(JInt(js, "last_glass_flag", 0));
        s->setFirstGlassFlag(JInt(js, "first_glass_flag", 0));
 
        if (js.isMember("qtime") && js["qtime"].isArray()) {
            for (int i = 0; i < 3; i++) {
                int v = (i < (int)js["qtime"].size()) ? js["qtime"][i].asInt() : 0;
                s->setQTime(i, v);
            }
        }
        else {
            for (int i = 0; i < 3; i++) s->setQTime(i, 0);
        }
        s->setQTimeOverFlag(JInt(js, "qtime_over_flag", 0));
 
        s->setMasterRecipe(JInt(js, "master_recipe", 0));
        if (js.isMember("device_recipe_ids") && js["device_recipe_ids"].isArray()) {
            for (int i = 0; i < DEVICE_COUNT; i++) {
                int v = (i < (int)js["device_recipe_ids"].size()) ? js["device_recipe_ids"][i].asInt() : 0;
                s->setDeviceRecipeId(i, static_cast<short>(v));
            }
        }
        else {
            for (int i = 0; i < DEVICE_COUNT; i++) s->setDeviceRecipeId(i, 0);
        }
 
        s->setPanelMeasure(JStr(js, "panel_measure").c_str());
        s->setMode(JInt(js, "mode", 0));
        s->setSlotUnitSelectFlag(JInt(js, "slot_unit_select_flag", 0));
 
        s->setSourcePortNo(JInt(js, "source_port_no", 0));
        s->setSourceSlotNo(JInt(js, "source_slot_no", 0));
        s->setTargetPortNo(JInt(js, "target_port_no", 0));
        s->setTargetSlotNo(JInt(js, "target_slot_no", 0));
 
        s->setProductJudge(static_cast<short>(JInt(js, "product_judge", 0)));
    }
 
    // path£ºË³ÐòÖØ½¨Á´£¨Ê±¼ä×Ö¶ÎÒÔ×Ö·û´®¶Á»Ø£©
    if (root.isMember("path") && root["path"].isArray()) {
        for (const auto& n : root["path"]) {
            unsigned eq = JUInt(n, "eq_id", 0);
            unsigned unit = JUInt(n, "unit", 0);
            unsigned slot = JUInt(n, "slot", 0);
            g.addPath(eq, unit, slot);
 
            CPath* tail = nullptr;
            if (auto head = g.getPath()) tail = head->getTailPath();
            if (!tail) continue;
 
            long long tin = 0, tout = 0;
            if (get_ll_from_json(n, "time_in", tin))  tail->setInTime(static_cast<ULONGLONG>(tin));
            if (get_ll_from_json(n, "time_out", tout)) tail->setOutTime(static_cast<ULONGLONG>(tout));
            tail->setInspResult(static_cast<InspResult>(JInt(n, "insp_result", 0)));
            if (JBool(n, "processed", false)) tail->processEnd();
        }
    }
 
    // SVÊý¾Ý£º·´ÐòÁл¯Èý²ã½á¹¹
    if (root.isMember("sv_datas") && root["sv_datas"].isObject()) {
        g.clearAllSVData(); // Çå¿ÕÏÖÓÐÊý¾Ý
 
        const auto& svDataObj = root["sv_datas"];
        auto memberNames = svDataObj.getMemberNames();
 
        for (const auto& machineIdStr : memberNames) {
            int machineId = std::stoi(machineIdStr);
            const auto& machineObj = svDataObj[machineIdStr];
 
            auto dataTypeNames = machineObj.getMemberNames();
            for (const auto& dataType : dataTypeNames) {
                const auto& dataArray = machineObj[dataType];
                if (dataArray.isArray()) {
                    for (const auto& itemObj : dataArray) {
                        long long timestampMs = 0;
                        double value = 0.0;
 
                        if (get_ll_from_json(itemObj, "t", timestampMs)) {
                            value = JDouble(itemObj, "v", 0.0);
                            // Ìí¼ÓSVÊý¾Ý
                            g.addSVData(machineId, dataType, timestampMs, value);
                        }
                    }
                }
            }
        }
    }
}
 
// ==================== ±ã½Ý·â×° ====================
 
std::string GlassJson::ToString(const CGlass& g) {
    Json::FastWriter w;              // ¾É°æ£º½ô´Õ£¬ÎÞ¸ñʽ
    // w.omitEndingLineFeed();          // È¥µôĩβ»»ÐУ¨Èç¹ûÄãµÄ JsonCpp °æ±¾Ö§³Ö£©
    return w.write(ToJson(g));
}
 
std::string GlassJson::ToPrettyString(const CGlass& g) {
    Json::StyledWriter w;            // ¾É°æ£ºÃÀ»¯Êä³ö
    return w.write(ToJson(g));
}
 
bool GlassJson::FromString(const std::string& text, CGlass& g, std::string* err) {
    Json::Reader reader;             // ¾É°æ½âÎöÆ÷
    Json::Value j;
    bool ok = reader.parse(text, j, /*collectComments*/ false);
    if (!ok) {
        if (err) *err = reader.getFormatedErrorMessages();
        return false;
    }
    FromJson(j, g);
    return true;
}