-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworker.cpp
More file actions
389 lines (326 loc) · 14.4 KB
/
Copy pathworker.cpp
File metadata and controls
389 lines (326 loc) · 14.4 KB
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
#include <iostream>
#include <QDebug>
#include <QException>
#include "worker.h"
#include "datatypes.h"
#define NSEC_PER_SECOND 1e+9
Worker::Worker(minas_control::MinasClient *_client,EngParameters*_engParameters, QObject* parent)
: QObject(parent)
, client(_client)
, engParameters(_engParameters)
{
// Set up real-time clock parameters
period = 4e+6; // 4ms period in nanoseconds
clock_gettime(CLOCK_REALTIME, &tick);
}
void Worker::threadMoveToHome() {
QString message;
if(!client )
{
message = "Cliente não inicializado. Não é possível mover para o home.";
emit sendLog(message);
return;
}
minas_control::MinasOutput output;
minas_control::MinasInput input;
if (client) {
client->setSwitchSpeed(engParameters->homing.switchSpeed);
client->setZeroSpeed(engParameters->homing.zeroSpeed);
client->setHomingAcceleration(engParameters->homing.homingAcceleration);
client->setHomingTorqueLimit(engParameters->homing.homingTorqueLimit);
client->setHomingDetectionTime(engParameters->homing.homingDetectionTime);
client->setHomingDetectionVelocity(engParameters->homing.homingDetectionVelocity);
client->setCommunicationFuntionExtendedSetup(engParameters->homing.communicationFunctionExtendedSetup);
client->setHomingReturnSpeedLimit(engParameters->homing.homingReturnSpeedLimit);
client->setHomingMode(engParameters->homing.homingMode); // (On Index Pulse +Ve direction)
client->setTouchProbe(engParameters->homing.touchprobeFunction);
threadEnableServo(0x06);
memset(&output, 0x00, sizeof(minas_control::MinasOutput));
output.max_motor_speed = engParameters->homing.max_motor_speed;
output.target_torque = engParameters->homing.target_torque;
output.max_torque = engParameters->homing.max_torque;
output.controlword = 0x001F;
output.operation_mode = 0x06; // definide de fato o modo de operação para a escrita
client->writeOutputs(output);
message = QString("🔄 Movendo servo para posição 0 -> Homing iniciado");
emit sendLog(message);
}
int iterationCount = 0;
while(true) // debug da operação
{
if(iterationCount>=20000){
emit sendLog("FALHA EM HOMING Target NOT reached!");
break;
}
input = threadReadInput();
output = threadReadOutput();
if(iterationCount % 10 ==0){
std::ostringstream logStream;
logStream << "err = " << std::hex << std::setw(8) << std::setfill('0') << input.error_code
<< ", ctrl = " << std::hex << std::setw(8) << std::setfill('0') << output.controlword
<< ", status = " << std::hex << std::setw(8) << std::setfill('0') << input.statusword
<< ", op_mode = " << std::hex << std::setw(8) << std::setfill('0') << input.operation_mode
<< ", pos = " << std::hex << std::setw(8) << std::setfill('0') << input.position_actual_value
<< ", vel = " << std::hex << std::setw(8) << std::setfill('0') << input.velocity_actual_value
<< ", tor = " << std::hex << std::setw(8) << std::setfill('0') << input.torque_actual_value
<< " -> interação: "<< iterationCount;
// emit sendLog(QString::fromStdString(logStream.str()));
}
if (input.statusword & 0x1000) { // Target reached
emit sendLog("✅ Target reached!");
break;
}
// Move to next tick
tick.tv_nsec += period;
while (tick.tv_nsec >= NSEC_PER_SECOND)
{
tick.tv_nsec -= NSEC_PER_SECOND;
tick.tv_sec++;
}
// detectar overrun de tempo
struct timespec before;
clock_gettime(CLOCK_REALTIME, &before);
double overrun_time = (before.tv_sec + double(before.tv_nsec) / 1e9) -
(tick.tv_sec + double(tick.tv_nsec) / 1e9);
if (overrun_time > 0.0) {
// emit sendLog(QString("⚠️ Overrun detected: %1 ms").arg(overrun_time * 1000));
}
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &tick, NULL); // esperar o prox tic
iterationCount++;
}
threadDisableServo();
emit sendLog("✅ Sucesso na operação de homing");
emit finished();
}
void Worker::threadMoveAbsoluteTo(double position, double velocity) {
QString message;
if(!client )
{
if(!client)
{
message = "Cliente não inicializado. Não é possível mover para o home.";
}
emit sendLog(message);
return;
}
minas_control::MinasOutput output;
minas_control::MinasInput input;
if (client) {
threadEnableServo(0x01);
memset(&output, 0x00, sizeof(minas_control::MinasOutput));
output.target_position = static_cast<int32_t>((0x800000 * position)/360);
output.max_motor_speed = static_cast<int32_t>(velocity);
output.target_torque = 500;
output.max_torque = 500;
output.controlword = 0x001F;
output.operation_mode = 0x01;
client->writeOutputs(output);
while (!(input.statusword & 0x1000))
{ // bit12 (set-point-acknowledge)
input = client->readInputs();
}
output.controlword &= ~0x0010; // clear new-set-point (bit4)
client->writeOutputs(output);
message = QString("🔄 Movendo servo para posição %1º | %2h | com velocidade %3")
.arg(QString::number(position, 'f',4))
.arg(QString::number(output.target_position, 16).toUpper())
.arg(velocity);
} else {
message = "Cliente não inicializado. Não é possível mover para a posição absoluta.";
emit sendLog(message);
return;
}
emit sendLog(message);
int iterationCount = 0;
while(true) // debug da operação
{
if(iterationCount>=20000)
break;
input = threadReadInput();
output = threadReadOutput();
if(iterationCount % 10 ==0){
std::ostringstream logStream;
logStream << "err = " << std::hex << std::setw(8) << std::setfill('0') << input.error_code
<< ", ctrl = " << std::hex << std::setw(8) << std::setfill('0') << output.controlword
<< ", status = " << std::hex << std::setw(8) << std::setfill('0') << input.statusword
<< ", op_mode = " << std::hex << std::setw(8) << std::setfill('0') << input.operation_mode
<< ", pos = " << std::hex << std::setw(8) << std::setfill('0') << input.position_actual_value
<< ", vel = " << std::hex << std::setw(8) << std::setfill('0') << input.velocity_actual_value
<< ", tor = " << std::hex << std::setw(8) << std::setfill('0') << input.torque_actual_value
<< " -> interação: "<< iterationCount;
// emit sendLog(QString::fromStdString(logStream.str()));
}
if (input.statusword & 0x0400) { // Target reached
emit sendLog("✅ Target reached!");
break;
}
// Move to next tick
tick.tv_nsec += period;
while (tick.tv_nsec >= NSEC_PER_SECOND)
{
tick.tv_nsec -= NSEC_PER_SECOND;
tick.tv_sec++;
}
// detectar overrun de tempo
struct timespec before;
clock_gettime(CLOCK_REALTIME, &before);
double overrun_time = (before.tv_sec + double(before.tv_nsec) / 1e9) -
(tick.tv_sec + double(tick.tv_nsec) / 1e9);
if (overrun_time > 0.0) {
// emit logMessage(QString("⚠️ Overrun detected: %1 ms").arg(overrun_time * 1000));
}
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &tick, NULL); // esperar o prox tic
iterationCount++;
}
threadDisableServo();
emit sendLog(QString("✅ Sucesso na operação para a posição atual: %1º | %2h | com velocidade %3")
.arg(QString::number(position,'f',4))
.arg(QString::number(input.position_actual_value,16).toUpper())
.arg(velocity));
emit finished();
}
void Worker::threadMoveOffset(double amount, double velocity, double step) {
QString message;
if(!client )
{
if(!client)
{
message = "Cliente não inicializado. Não é possível fazer o jog.";
}
emit sendLog(message);
return;
}
minas_control::MinasOutput output;
minas_control::MinasInput input;
int32_t offset_units = static_cast<int32_t>((amount * step) * (0x800000 / 360.0));
if (client) {
threadEnableServo(0x01);
input = client->readInputs();
memset(&output, 0x00, sizeof(minas_control::MinasOutput));
output.target_position = static_cast<int32_t>(input.position_actual_value) + offset_units;
output.max_motor_speed = static_cast<int32_t>(velocity);
output.target_torque = engParameters->positioning.targetTorque;
output.max_torque = engParameters->positioning.maxTorque;
output.controlword = 0x001F;
output.operation_mode = 0x01;
std::cout << "-> output.target_position: " << output.target_position << "| input.position_actual_value: " <<input.position_actual_value << "\n";
client->writeOutputs(output);
while (!(input.statusword & 0x1000))
{ // bit12 (set-point-acknowledge)
input = client->readInputs();
}
output.controlword &= ~0x0010; // clear new-set-point (bit4)
client->writeOutputs(output);
message = QString("🔄 Movendo servo para posição de %1º | %2h | com velocidade %3")
.arg(QString::number(amount*step, 'f',4))
.arg(QString::number(output.target_position, 16).toUpper())
.arg(velocity);
} else {
message = "Cliente não inicializado. Não foi possivel executar executar o posicionamento relativo.";
emit sendLog(message);
return;
}
emit sendLog(message);
int iterationCount = 0;
while(true) // debug da operação
{
if(iterationCount>=20000)
break;
input = threadReadInput();
output = threadReadOutput();
if(iterationCount % 10 ==0){
std::ostringstream logStream;
logStream << "err = " << std::hex << std::setw(8) << std::setfill('0') << input.error_code
<< ", ctrl = " << std::hex << std::setw(8) << std::setfill('0') << output.controlword
<< ", status = " << std::hex << std::setw(8) << std::setfill('0') << input.statusword
<< ", op_mode = " << std::hex << std::setw(8) << std::setfill('0') << input.operation_mode
<< ", pos = " << std::hex << std::setw(8) << std::setfill('0') << input.position_actual_value
<< ", vel = " << std::hex << std::setw(8) << std::setfill('0') << input.velocity_actual_value
<< ", tor = " << std::hex << std::setw(8) << std::setfill('0') << input.torque_actual_value
<< " -> interação: "<< iterationCount;
// emit sendLog(QString::fromStdString(logStream.str()));
}
if (input.statusword & 0x0400) { // Target reached
emit sendLog("✅ Target reached!");
break;
}
// Move to next tick
tick.tv_nsec += period;
while (tick.tv_nsec >= NSEC_PER_SECOND)
{
tick.tv_nsec -= NSEC_PER_SECOND;
tick.tv_sec++;
}
// detectar overrun de tempo
struct timespec before;
clock_gettime(CLOCK_REALTIME, &before);
double overrun_time = (before.tv_sec + double(before.tv_nsec) / 1e9) -
(tick.tv_sec + double(tick.tv_nsec) / 1e9);
if (overrun_time > 0.0) {
// emit logMessage(QString("⚠️ Overrun detected: %1 ms").arg(overrun_time * 1000));
}
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &tick, NULL); // esperar o prox tic
iterationCount++;
}
threadDisableServo();
emit sendLog(QString("✅ Sucesso na operação para a posição relativa em %1º | Atual: %2h | com velocidade %3")
.arg(QString::number(amount*step, 'f',4))
.arg(QString::number(input.position_actual_value, 16).toUpper())
.arg(velocity));
emit finished();
}
//funções privadas
void Worker::threadDisableServo() {
QString message;
if (client) {
minas_control::MinasInput input;
input = threadReadInput();
client->printPDSStatus(input);
client->printPDSOperation(input);
client->servoOff();
message = "Servo desabilitado.";
} else {
message = "Cliente não inicializado. Não é possível desabilitar o servo.";
}
emit sendLog(message);
}
void Worker::threadEnableServo(int mode) {
QString message;
if (client) {
try{
client->servoOn(mode);
client->setProfileVelocity(0x16000000);
client->setProfileAcceleration(0x80000000);
client->setProfileDeceleration(0x80000000);
QString name_mode;
if (mode == 0x01) {
name_mode = "Posição absoluta";
} else if (mode == 0x06) {
name_mode = "Homing position";
} else {
name_mode = QString("Modo desconhecido: %1").arg(mode); // Lidar com modos desconhecidos
}
message = QString("Servo habilitado no modo %1|%2").arg(mode).arg(name_mode);
// configurar as acelerações e velocidades de perfil. Não alterar
}
catch(const QException &e){
message = QString("Erro: ") + QString(e.what());
}
}
else {
message = "Cliente não inicializado. Não é possível habilitar o servo.";
}
emit sendLog(message);
}
minas_control::MinasInput Worker::threadReadInput(){
minas_control::MinasInput input;
input = client->readInputs();
emit inputChangedSignalThread(input);
return input;
}
minas_control::MinasOutput Worker::threadReadOutput(){
minas_control::MinasOutput output;
output = client->readOutputs();
// emit outputChangedSignal(output); // não usado por enquanto
return output;
}