-
Notifications
You must be signed in to change notification settings - Fork 8
/
ZQRCode.prw
3130 lines (2678 loc) · 93.8 KB
/
ZQRCode.prw
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -------------------------------------------------------------------------------------------
Copyright 2015-2019 Júlio Wittwer ( siga0984@gmail.com | http://siga0984.wordpress.com/ )
É permitido, gratuitamente, a qualquer pessoa que obtenha uma cópia deste software
e dos arquivos de documentação associados (o "Software"), para negociar o Software
sem restrições, incluindo, sem limitação, os direitos de uso, cópia, modificação, fusão,
publicação, distribuição, sublicenciamento e/ou venda de cópias do Software,
SEM RESTRIÇÕES OU LIMITAÇÕES.
O SOFTWARE É FORNECIDO "TAL COMO ESTÁ", SEM GARANTIA DE QUALQUER TIPO, EXPRESSA OU IMPLÍCITA,
INCLUINDO MAS NÃO SE LIMITANDO A GARANTIAS DE COMERCIALIZAÇÃO, ADEQUAÇÃO A UMA FINALIDADE
ESPECÍFICA E NÃO INFRACÇÃO. EM NENHUM CASO OS AUTORES OU TITULARES DE DIREITOS AUTORAIS
SERÃO RESPONSÁVEIS POR QUALQUER REIVINDICAÇÃO, DANOS OU OUTRA RESPONSABILIDADE, SEJA
EM AÇÃO DE CONTRATO OU QUALQUER OUTRA FORMA, PROVENIENTE, FORA OU RELACIONADO AO SOFTWARE.
*** USE A VONTADE, POR SUA CONTA E RISCO ***
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, WITHOUT RESTRICTIONS OR LIMITATIONS.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE.
***USE AS YOU WISH , AT YOUR OWN RISK ***
------------------------------------------------------------------------------------------- */
#include 'protheus.ch'
#include 'zlib.ch'
/*
=== Referencias da implementação ===
https://www.qr-code-generator.com/
https://www.qrcode.com/en/codes/
https://en.wikipedia.org/wiki/QR_code
https://www.thonky.com/qr-code-tutorial/introduction
https://www.thonky.com/qr-code-tutorial/module-placement-matrix
https://www.thonky.com/qr-code-tutorial/alignment-pattern-locations
https://www.thonky.com/qr-code-tutorial/format-version-information
https://www.thonky.com/qr-code-tutorial/data-masking
https://www.thonky.com/qr-code-tutorial/mask-patterns
Referencias de correção de erro
https://www.thonky.com/qr-code-tutorial/error-correction-coding
https://www.thonky.com/qr-code-tutorial/generator-polynomial-tool?degree=10
https://github.com/zxing/zxing/tree/00f634024ceeee591f54e6984ea7dd666fab22ae/cpp
https://github.com/ArashPartow/schifra
https://archive.codeplex.com/?p=schifra
https://stackoverflow.com/questions/11243272/error-correcting-codes
http://www.drdobbs.com/cpp/reed-solomon-error-correction/184410107
*/
// ===============================================================
CLASS ZQRCODE FROM LONGNAMECLASS
DATA nVersion // Versao do QR Code ( 1-40 )
DATA nSize // Aresta do QR Code
DATA aGrid // Grid de modulos do QR Code
DATA cQRData // Dados da mensagem
DATA cErrCorr // Correção de erro ( LMQH )
DATA nMask // Data Mask ( 0-7 )
DATA nMode // Encoding Mode ( Alfanumerico=2 )
DATA aBitStream // CodeWord final ( Dados + Error Correction )
DATA oLogger
DATA lVerbose
METHOD NEW()
METHOD SetEC()
METHOD SetData()
METHOD BuildData()
METHOD DeployBits()
METHOD SelectMask()
METHOD PutAlign()
METHOD BuildErrData()
METHOD BestVersion()
METHOD PutFVInfo()
METHOD GetCountSize()
METHOD PrintQR()
METHOD PrintBits()
METHOD ApplyMask()
ENDCLASS
// ------------------------------------------
// Cria um objeto para manipulação de um QR Code
METHOD NEW() CLASS ZQRCODE
::nVersion := 0
::nSize := 0
::aGrid := {}
::cQRData := ''
::cErrCorr := 'L'
::nMode := 0
::lVerbose := .F.
::oLogger := ZLOGGER():New("ZQRCODE")
::oLogger:Write("NEW","New QRCode Object")
Return self
// ------------------------------------------
// Para a criação de um QR Code, o primeiro métoo a ser chamado
// é a definição do nivel de correção de erro
// Caso nao chamado, o default é "L" ( Low )
METHOD SetEC(cErrCorr) CLASS ZQRCODE
IF ::lVerbose
::oLogger:Write("SetEC","Error Correction set to ["+cErrCorr+"]")
Endif
::cErrCorr := cErrCorr
Return
// ------------------------------------------
// A Criação do QR Code envolve a codificaçao
// de dados, logo devemos informar a string
// a ser representada no QR Code, e opcionalmente
// o modo de codificacão. Atualmente são suportados
// os métodos 2 ( alfanumérico ) e 3 ( ASCII Bytes / UTF8 )
METHOD SetData(cStr,nMode) CLASS ZQRCODE
::oLogger:Write("SETDATA","Set Data ["+cValToChar(cStr)+"]")
::cQRData := cStr
IF nMode != NIL
// Modo informado como parametro
::nMode := nMode
Else
// TODO - chumbado por enquando bytes
// O Correto é verificar se a mensagem cabe dentro de um determnado
// modo de codificacao ( numerico, alfa, bytes ) segundo o Error Correction definido
::nMode := 3
Endif
::oLogger:Write("SETDATA","Data Mode ["+cValToChar(nMode)+"]")
Return
// ------------------------------------------
// Imprime QR Code em modo de depuração no console
METHOD PrintBits() CLASS ZQRCODE
Local nL , nC , cRow
conout('')
For nL := 1 to len(::aGrid)
cRoW := ''
For nC := 1 to len(::aGrid[nL])
IF ::aGrid[nL][nC] > 0
IF ::aGrid[nL][nC] = 1
cRow += chr(178)+chr(178)
ElseIF ::aGrid[nL][nC] = 2
cRow += ' '
ElseIF ::aGrid[nL][nC] = 3
cRow += chr(219)+chr(219)
Endif
ElseIf ::aGrid[nL][nC] = 0
cRow += chr(176)+chr(176)
Else
cRow += '--'
Endif
Next
conout(cRow)
Next
conout('')
Return
// ------------------------------------------
// Imprime QR Code no console em modo pseudo-grafico
METHOD PrintQR(aGrid) CLASS ZQRCODE
Local nL , nC , cRow
Local lSet1
Local lSet2
conout(replicate('-',::nSize))
Conout('')
IF pcount() == 0
aGrid := ::aGrid
Endif
For nL := 1 to len(aGrid) step 2
cRoW := ''
For nC := 1 to len(aGrid[nL])
lSet1 := aGrid[nL][nC] == 1 .or. aGrid[nL][nC] == 3
IF nL+1>::nSize
lSet2 := .F.
Else
lSet2 := aGrid[nL+1][nC] == 1 .or. aGrid[nL+1][nC] == 3
Endif
if lset1 .and. lset2
cRow += chr(219) // full block
ElseIf lset1 .and. !lset2
cRow += chr(223) // upper half
ElseIf !lset1 .and. lset2
cRow += chr(220) // lower half
Else
cRow += ' ' // empty
Endif
Next
conout(cRow)
Next
conout('')
Return
// ------------------------------------------------------------
// Função auxiliar PutArray()
// Plota dentro do array de destino, nas coordenadas informadas
// em nLine e nCol o array de origem. se e somente se
// o array de origem na posição informada appenas
// atualizar coordenadas nao inicializadas ou usadas (-1)
// Util para colocar os patterns de localização e alinhamento
STATIC Function PutArray(aTarget,aSource,nLine,nCol)
Local nL , nC
Local lOk := .T.
// Primeiro verifica se algum ponto já está preenchido
For nL := 1 to len(aSource)
For nC := 1 to len(aSource[nL])
IF aTarget[nLine+nL-1][nCol+nC-1] >= 0
lOk := .F.
EXIT
Endif
Next
IF !lOk
EXIT
Endif
Next
If lOk
// Todas as coordenadas livres, aplica o array
For nL := 1 to len(aSource)
For nC := 1 to len(aSource[nL])
aTarget[nLine+nL-1][nCol+nC-1] := aSource[nL][nC]
Next
Next
Endif
Return lOk
// ------------------------------------------------------------
// Monta e inicializa um Grid de um determinado tamanho
// Já plota no Grid os Patterns de Localização,
// as Time Lines e o Dark Pattern
STATIC Function BuildGrid(nSize)
Local aGrid := {}, aRow := {}
Local nI
For nI := 1 to nSize
aadd(aRow,-1)
Next
For nI := 1 to nSize
aadd(aGrid,aClone(aRow))
Next
return aGrid
// ------------------------------------------------------------
// Calcula o tamanho da aresta do QR Code de acordo com a versao
// 21 , 25 , 29 ... ( cresce em passos de 4 )
STATIC Function VerSize(nVersion)
Return ( 17 + ( 4*nVersion ) )
// ------------------------------------------------------------
// Plota os patterns de alinhamento no Grid
// de acordo com as coordenadas infomadas
METHOD PutAlign( aAlignPos , aAlign ) CLASS ZQRCODE
Local nL , nC
Local nT := len(aAlignPos)
For nL := 1 TO nT
For nC := 1 to nT
::oLogger:Write("BUILDDATA","Put Alignment pattern at ["+cValToChar(aAlignPos[nL]-1)+","+cValToChar(aAlignPos[nC]-1)+"]")
PutArray(::aGrid,aAlign,aAlignPos[nL]-1,aAlignPos[nC]-1 )
Next
Next
Return
// ------------------------------------------------------------
// Obtem as coordenadas dos padroes de alinhamento por versao
// Coordenadas em {Linha,Coluna}
STATIC __CenterAlign
STATIC Function GetCenterAlign(nVersion)
IF __CenterAlign = NIL
_CenterAlign := {}
aadd(_CenterAlign,{6,18}) // Version 2
aadd(_CenterAlign,{6,22}) // Version 3
aadd(_CenterAlign,{6,26}) // Version 4
aadd(_CenterAlign,{6,30}) // Version 5
aadd(_CenterAlign,{6,34}) // Version 6
aadd(_CenterAlign,{6,22,38}) // Version 7
aadd(_CenterAlign,{6,24,42}) // Version 8
aadd(_CenterAlign,{6,26,46}) // Version 9
aadd(_CenterAlign,{6,28,50}) // Version 10
aadd(_CenterAlign,{6,30,54}) // Version 11
aadd(_CenterAlign,{6,32,58}) // Version 12
aadd(_CenterAlign,{6,34,62}) // Version 13
aadd(_CenterAlign,{6,26,46,66}) // Version 14
aadd(_CenterAlign,{6,26,48,70}) // Version 15
aadd(_CenterAlign,{6,26,50,74}) // Version 16
aadd(_CenterAlign,{6,30,54,78}) // Version 17
aadd(_CenterAlign,{6,30,56,82}) // Version 18
aadd(_CenterAlign,{6,30,58,86}) // Version 19
aadd(_CenterAlign,{6,34,62,90}) // Version 20
aadd(_CenterAlign,{6,28,50,72,94}) // Version 21
aadd(_CenterAlign,{6,26,50,74,98}) // Version 22
aadd(_CenterAlign,{6,30,54,78,102}) // Version 23
aadd(_CenterAlign,{6,28,54,80,106}) // Version 24
aadd(_CenterAlign,{6,32,58,84,110}) // Version 25
aadd(_CenterAlign,{6,30,58,86,114}) // Version 26
aadd(_CenterAlign,{6,34,62,90,118}) // Version 27
aadd(_CenterAlign,{6,26,50,74,98,122}) // Version 28
aadd(_CenterAlign,{6,30,54,78,102,126}) // Version 29
aadd(_CenterAlign,{6,26,52,78,104,130}) // Version 30
aadd(_CenterAlign,{6,30,56,82,108,134}) // Version 31
aadd(_CenterAlign,{6,34,60,86,112,138}) // Version 32
aadd(_CenterAlign,{6,30,58,86,114,142}) // Version 33
aadd(_CenterAlign,{6,34,62,90,118,146}) // Version 34
aadd(_CenterAlign,{6,30,54,78,102,126,150}) // Version 35
aadd(_CenterAlign,{6,24,50,76,102,128,154}) // Version 36
aadd(_CenterAlign,{6,28,54,80,106,132,158}) // Version 37
aadd(_CenterAlign,{6,32,58,84,110,136,162}) // Version 38
aadd(_CenterAlign,{6,26,54,82,110,138,166}) // Version 39
aadd(_CenterAlign,{6,30,58,86,114,142,170}) // Version 40
Endif
Return _CenterAlign[nVersion-1]
STATIC _Alpha := GetAlpha()
// ------------------------------------------------------------
// Obtém o alfabeto Alfanumérico ( restrito ) para codificação
STATIC Function GetAlpha()
IF _Alpha = NIL
_Alpha := {}
aadd(_Alpha,{'0', 0 })
aadd(_Alpha,{'1', 1 })
aadd(_Alpha,{'2', 2 })
aadd(_Alpha,{'3', 3 })
aadd(_Alpha,{'4', 4 })
aadd(_Alpha,{'5', 5 })
aadd(_Alpha,{'6', 6 })
aadd(_Alpha,{'7', 7 })
aadd(_Alpha,{'8', 8 })
aadd(_Alpha,{'9', 9 })
aadd(_Alpha,{'A', 10 })
aadd(_Alpha,{'B', 11 })
aadd(_Alpha,{'C', 12 })
aadd(_Alpha,{'D', 13 })
aadd(_Alpha,{'E', 14 })
aadd(_Alpha,{'F', 15 })
aadd(_Alpha,{'G', 16 })
aadd(_Alpha,{'H', 17 })
aadd(_Alpha,{'I', 18 })
aadd(_Alpha,{'J', 19 })
aadd(_Alpha,{'K', 20 })
aadd(_Alpha,{'L', 21 })
aadd(_Alpha,{'M', 22 })
aadd(_Alpha,{'N', 23 })
aadd(_Alpha,{'O', 24 })
aadd(_Alpha,{'P', 25 })
aadd(_Alpha,{'Q', 26 })
aadd(_Alpha,{'R', 27 })
aadd(_Alpha,{'S', 28 })
aadd(_Alpha,{'T', 29 })
aadd(_Alpha,{'U', 30 })
aadd(_Alpha,{'V', 31 })
aadd(_Alpha,{'W', 32 })
aadd(_Alpha,{'X', 33 })
aadd(_Alpha,{'Y', 34 })
aadd(_Alpha,{'Z', 35 })
aadd(_Alpha,{' ', 36 }) // (space)
aadd(_Alpha,{'$', 37 })
aadd(_Alpha,{'%', 38 })
aadd(_Alpha,{'*', 39 })
aadd(_Alpha,{'+', 40 })
aadd(_Alpha,{'-', 41 })
aadd(_Alpha,{'.', 42 })
aadd(_Alpha,{'/', 43 })
aadd(_Alpha,{':', 44 })
Endif
Return _Alpha
// ----------------------------------------------------------
// Modos de codificação e sequencia binária correspondente
STATIC _Modes := GetAModes()
STATIC Function GetAModeS()
Local aModes := {}
// Mode Name Mode Indicator
aadd(aModes,{'Numeric Mode' ,'0001'})
aadd(aModes,{'Alphanumeric Mode','0010'})
aadd(aModes,{'Byte Mode' ,'0100'})
aadd(aModes,{'Kanji Mode' ,'1000'})
// missing info ....
// aadd(_Modes,{'ECI Mode' ,'0111'})
return aModes
// ------------------------------------------------------------
// Obtem o numero de bits necessarios para representar
// o tamanho dos dados do QR Code de acordo com a versão
METHOD GetCountSize() CLASS ZQRCODE
Local nBits := 0
IF ::nVersion >= 1 .and. ::nVersion <= 9
IF ::nMode == 1
nBits := 10
ElseIF ::nMode == 2
nBits := 9
ElseIF ::nMode == 3
nBits := 8
ElseIF ::nMode == 4
nBits := 8
Endif
ElseIF ::nVersion >= 10 .and. ::nVersion <= 26
IF ::nMode == 1
nBits := 12
ElseIF ::nMode == 2
nBits := 11
ElseIF ::nMode == 3
nBits := 16
ElseIF ::nMode == 4
nBits := 10
Endif
ElseIF ::nVersion >= 10 .and. ::nVersion <= 26
IF ::nMode == 1
nBits := 14
ElseIF ::nMode == 2
nBits := 13
ElseIF ::nMode == 3
nBits := 16
ElseIF ::nMode == 4
nBits := 12
Endif
Endif
::oLogger:Write("GETCOUNTSIZE","Bit Size for Version ["+cValToChar(::nVersion)+"] Mode ["+cValTochar(::nMode)+"] is "+cValToChar(nBits))
Return nBits
// Encoding modes
// https://www.thonky.com/qr-code-tutorial/numeric-mode-encoding
// https://www.thonky.com/qr-code-tutorial/alphanumeric-mode-encoding
// https://www.thonky.com/qr-code-tutorial/byte-mode-encoding
// --------------------------------------------------------------
// Monta a tabela de formato e versao em cache
// https://www.thonky.com/qr-code-tutorial/format-version-tables
// List of all Format Information Strings
// [1] ECC Level [2] Mask Pattern [3] Type Information Bits
STATIC _InfoStr := GetFmtInfo()
STATIC Function GetFmtInfo()
Local aInfoStr := {}
If _InfoStr = NIL
aadd(aInfoStr,{'L',0,'111011111000100'})
aadd(aInfoStr,{'L',1,'111001011110011'})
aadd(aInfoStr,{'L',2,'111110110101010'})
aadd(aInfoStr,{'L',3,'111100010011101'})
aadd(aInfoStr,{'L',4,'110011000101111'})
aadd(aInfoStr,{'L',5,'110001100011000'})
aadd(aInfoStr,{'L',6,'110110001000001'})
aadd(aInfoStr,{'L',7,'110100101110110'})
aadd(aInfoStr,{'M',0,'101010000010010'})
aadd(aInfoStr,{'M',1,'101000100100101'})
aadd(aInfoStr,{'M',2,'101111001111100'})
aadd(aInfoStr,{'M',3,'101101101001011'})
aadd(aInfoStr,{'M',4,'100010111111001'})
aadd(aInfoStr,{'M',5,'100000011001110'})
aadd(aInfoStr,{'M',6,'100111110010111'})
aadd(aInfoStr,{'M',7,'100101010100000'})
aadd(aInfoStr,{'Q',0,'011010101011111'})
aadd(aInfoStr,{'Q',1,'011000001101000'})
aadd(aInfoStr,{'Q',2,'011111100110001'})
aadd(aInfoStr,{'Q',3,'011101000000110'})
aadd(aInfoStr,{'Q',4,'010010010110100'})
aadd(aInfoStr,{'Q',5,'010000110000011'})
aadd(aInfoStr,{'Q',6,'010111011011010'})
aadd(aInfoStr,{'Q',7,'010101111101101'})
aadd(aInfoStr,{'H',0,'001011010001001'})
aadd(aInfoStr,{'H',1,'001001110111110'})
aadd(aInfoStr,{'H',2,'001110011100111'})
aadd(aInfoStr,{'H',3,'001100111010000'})
aadd(aInfoStr,{'H',4,'000011101100010'})
aadd(aInfoStr,{'H',5,'000001001010101'})
aadd(aInfoStr,{'H',6,'000110100001100'})
aadd(aInfoStr,{'H',7,'000100000111011'})
_InfoStr := aInfoStr
Endif
Return _InfoStr
// --------------------------------------------------------------
// Para montar a sequencia reservada de 15 bits de um QRCode
// informe o error correcion e o Mask utilizad, e a função
// retorna os 15 bits ( como string de "0" e "1" a acrecentar
STATIC Function GetTypeBits(cErrCorr,nMask)
Local nPos
nPos := ascan( _InfoStr , {|x| x[1] == cErrCorr .and. x[2] == nMask })
If nPos > 0
Return _InfoStr[nPos][3]
Endif
Return ''
// ----------------------------------------------------------------
// A partir dos 15 bis de informaçáo do Error Code e Mask
// disposta em um QRCode, determina o error code e a mascara em uso
// retorna ambos por referencia
// Usado em leitura de QRCode
STATIC Function GetBitsEM(cFmtInfo,cErrCorr,nMask)
Local nPos
nPos := ascan( _InfoStr , {|x| x[3] == cFmtInfo })
If nPos > 0
cErrCorr := _InfoStr[nPos][1]
nMAsk := _InfoStr[nPos][2]
Return .T.
Endif
Return .F.
// --------------------------------------------------------------
// Na geração de um QRCode, após definir os dados
// esta função gera o array de bytes em string binaria
// codificando os dados e fazendo o "padding" de acordo
// com as propriedades do QRCode
METHOD BuildData() CLASS ZQRCODE
Local aPattern1 := {} // top left pattern position
Local aPattern2 := {} // top right pattern position
Local aPattern3 := {} // bottom left pattern position
Local aAlignMask := {}
Local aAlignPos := {}
Local nL , nC
Local aAlphaTab
Local aModes
Local nI
Local cChar, nPos, nVal
Local cDataBits := ''
Local cBitSize , nCntBits, nDataSize
Local nErrCW
Local aQRErrData := {}
Local aFinalData := {}
Local nInt
Local nBlocks1, nData1
Local nBlocks2, nData2
Local nTotData
Local aBitsBlk := {}
Local aGrupos,aErrors,nPosData
Local nB
Local cBitVinfo
Local aVinfoBL := {} // Boottom left
Local aVInfoTR := {} // Top Right
If ::nVersion < 1
// Se até agora nao tinha a versão, escolhe
// a melhor de acordo com o error correction
// e tamanho dos dados de acordo com o modo de codificaçcão
::nVersion := ::BestVersion()
Endif
::oLogger:Write("BUILDDATA","Building Data for Version ["+cValToChar(::nVersion)+"]")
// Pega o tamanho da aresta do QR Code baseado na versão
::nSize := VerSize(::nVersion)
::oLogger:Write("BUILDDATA","QR Code Size ["+cValToChar(::nSize)+"]")
// Monta o Grid em array bi-dimensional com elementos
// inicializados com -1 ( elemento livre)
::aGrid := BuildGrid( ::nSize )
// Localizador superior esquerdo
aadd(aPattern1,{1,1,1,1,1,1,1,0})
aadd(aPattern1,{1,0,0,0,0,0,1,0})
aadd(aPattern1,{1,0,1,1,1,0,1,0})
aadd(aPattern1,{1,0,1,1,1,0,1,0})
aadd(aPattern1,{1,0,1,1,1,0,1,0})
aadd(aPattern1,{1,0,0,0,0,0,1,0})
aadd(aPattern1,{1,1,1,1,1,1,1,0})
aadd(aPattern1,{0,0,0,0,0,0,0,0})
// Localizador superior direito
aadd(aPattern2,{0,1,1,1,1,1,1,1})
aadd(aPattern2,{0,1,0,0,0,0,0,1})
aadd(aPattern2,{0,1,0,1,1,1,0,1})
aadd(aPattern2,{0,1,0,1,1,1,0,1})
aadd(aPattern2,{0,1,0,1,1,1,0,1})
aadd(aPattern2,{0,1,0,0,0,0,0,1})
aadd(aPattern2,{0,1,1,1,1,1,1,1})
aadd(aPattern2,{0,0,0,0,0,0,0,0})
// Localizador inferior esquerdo
aadd(aPattern3,{0,0,0,0,0,0,0,0})
aadd(aPattern3,{1,1,1,1,1,1,1,0})
aadd(aPattern3,{1,0,0,0,0,0,1,0})
aadd(aPattern3,{1,0,1,1,1,0,1,0})
aadd(aPattern3,{1,0,1,1,1,0,1,0})
aadd(aPattern3,{1,0,1,1,1,0,1,0})
aadd(aPattern3,{1,0,0,0,0,0,1,0})
aadd(aPattern3,{1,1,1,1,1,1,1,0})
// Coloca os Finder Patterns no lugar
// de acordo com o tamanho do QRCode
PutArray(::aGrid,aPattern1,01,01 )
PutArray(::aGrid,aPattern2,01,::nSize-7)
PutArray(::aGrid,aPattern3,::nSize-7,01 )
// Seta o Dark Pointer
// ( primeiro byte apos o localizador inferior esquerdo )
nL := ::nSize-7
nC := 09
::aGrid[nL,nC] := 1
::oLogger:Write("BUILDDATA","Set Dark Pointer at ["+cValToChar(nL-1)+","+cValToChar(nC-1)+"]")
// Cria e coloca os Align Patterns
// Para versão 2 em diante
// Os padroes de alinhamento devem ser distribuidos
// por versao em coordenadas centrais pré-estabelecidas
// e não podem "colidir" com os localizadores
If ::nVersion > 1
// Cria o padrao de alinhamento
aadd(aAlignMask,{1,1,1,1,1})
aadd(aAlignMask,{1,0,0,0,1})
aadd(aAlignMask,{1,0,1,0,1})
aadd(aAlignMask,{1,0,0,0,1})
aadd(aAlignMask,{1,1,1,1,1})
// Versa 2 ou maior, exige alinhamento
aAlignPos := GetCenterAlign(::nVersion)
// Coloca os padroes de alinhamento no Grid
::PutAlign( aAlignPos , aAlignMask )
Endif
If ::nVersion > 6
// Versao 7 em diante, reserva a área em volta do localizador
// superior direito e inferior esquerdo para "Version Information"
// Reserve the Version Information Area
// QR codes versions 7 and larger must contain two areas where version information bits are placed.
// The areas are a 6x3 block above the bottom-left finder pattern and a 3x6 block to the left of the
// top-right finder pattern. The following images show the locations of the reserved areas in blue.
cBitVinfo := GetVInfo(::nVersion)
aVinfoBL := {} // Boottom left
aVInfoTR := {} // Top Right
aadd(aVinfoBL,{00,03,06,09,12,15})
aadd(aVinfoBL,{01,04,07,10,13,16})
aadd(aVinfoBL,{02,05,08,11,14,17})
aadd(aVinfoTR,{00,01,02})
aadd(aVinfoTR,{03,04,05})
aadd(aVinfoTR,{06,07,08})
aadd(aVinfoTR,{09,10,11})
aadd(aVinfoTR,{12,13,14})
aadd(aVinfoTR,{15,16,17})
For nL := 1 to len(aVinfoBL)
For nC := 1 to len(aVinfoBL[nL])
aVinfoBL[nL][nC] := val(substr(cBitVInfo,18-aVinfoBL[nL][nC],1))
NExt
Next
PutArray(::aGrid,aVinfoBL,::nSize-10,01 )
For nL := 1 to len(aVinfoTR)
For nC := 1 to len(aVinfoTR[nL])
aVinfoTR[nL][nC] := val(substr(cBitVInfo,18-aVinfoTR[nL][nC],1))
NExt
Next
PutArray(::aGrid,aVinfoBL,01,::nSize-10)
Endif
// Coloca as Time Lines
// TimeLine vertical, liga os patterns 1 e 3
For nL := 9 to ::nSize-8 STEP 2
::aGrid[nL,7] := 1
Next
For nL := 8 to ::nSize-7 STEP 2
::aGrid[nL,7] := 0
Next
// TimeLine Horizontal, liga os patterns 1 e 2
For nC := 9 to ::nSize-8 STEP 2
::aGrid[7,nC] := 1
Next
For nC := 8 to ::nSize-7 STEP 2
::aGrid[7,nC] := 0
Next
// Recupera o array de modos
// [1] DEscricao [2] Bits
// agora vamos mastigar os dados e gerar bits
// primeiro acrescenta o modo em uso nos dados
aModes := GetAModes()
// OS 4 primeiros bits do stream começam com
// o modo ou tipo da codificaçao ( alfanumerica, bytes, ... )
cDataBits := aModes[::nMode][2]
::oLogger:Write("BUILDDATA","Encoding Mode Bits ........ "+aModes[::nMode][2]+ " ("+aModes[::nMode][1]+")")
// Determina tamanho dos dados
nDataSize := len(::cQRData)
::oLogger:Write("BUILDDATA","Data Buffer ............... ["+::cQRData+"] ")
::oLogger:Write("BUILDDATA","Data Size ................ "+cValToChar(nDataSize) )
// Converte o tamanho pra binario em 16 bits
cBitSize := NTOBIT16(nDataSize)
// Agora determina quantos bits devem ser usados para
// representar o tamanho
nCntBits := ::GetCountSize()
// Corta o tamanho no nimero de bits necessarios
cBitSize := substr(cBitSize,17-nCntBits)
::oLogger:Write("BUILDDATA","Data Size Bits ............ "+cBitSize+" ("+cValToChar(nCntBits)+" bits long)")
// E acrescenta no stream de bits de dados
cDataBits += cBitSize
If ::nMode == 2
// Modo Alfanumerico
// Codificação Alfanumerica com Alfabeto Restrito
// Recupera o alfabeto
aAlphaTab := GetAlpha()
aChars := {-1,-1}
// Varre os dados para codificar
For nI := 1 to nDataSize
// Pega o caactere, busca a posicao no alfabeto
cChar := upper(substr(::cQRData,nI,1))
nPos := ascan(aAlphaTab,{|x| x[1] == cChar })
IF nPos == 0
USerException("Char ["+cChar+"] not found on alphanumeric table.")
Endif
// Pega o valor a ser codificado
nVal := aAlphaTab[nPos][2]
::oLogger:Write("BUILDDATA","Char #"+cValToChar(nI)+ " ["+cChar+"] Alpha Value ["+cValToChar(nVal)+"]")
// Monta um par de valores
IF aChars[1] == -1
aChars[1] := nVal
Else
aChars[2] := nVal
nTuple := ( aChars[1] * 45 ) + aChars[2]
cCodeBits := Substr( NTOBIT16( nTuple ) , 6 )
::oLogger:Write("BUILDDATA","Tuple ("+cValToChar(nTuple)+") Char Bits ["+cCodeBits+"]")
cDataBits += cCodeBits
aChars := {-1,-1}
Endif
Next
IF aChars[1] > 0
// ultimo cactere, sem par
// Converte direto para binario em 6 bits
cCodeBits := Substr(NTOBIT8(aChars[1]),3)
::oLogger:Write("BUILDDATA","Last Char 6 Bits ["+cCodeBits+"]")
cDataBits += cCodeBits
Endif
ElseIf ::nMode == 3 // Codificação em Bytes ( ASCII / UTF8 )
// Codificação em Bytes, a mais simples
For nI := 1 to nDataSize
cChar := substr(::cQRData,nI,1)
nChar := asc(cChar)
cCodeBits := NTOBIT8( nChar )
::oLogger:Write("BUILDDATA","Char #"+cValToChar(nI)+ " ["+cChar+"] Bits ["+cCodeBits+"]")
cDataBits += cCodeBits
Next
Else
UserException("MODE ["+cValToChar(::nMode)+"] NOT IMPLEMENTED")
Endif
::oLogger:Write("BUILDDATA","Encode Buffer Bits ........ "+cDataBits)
nBitSize := len(cDataBits)
::oLogger:Write("BUILDDATA","Encode Bits Size .......... "+cValToChar(nBitSize))
/*
GetECCW()
1) Version and EC Level
2) Total Number of Data Codewords for this Version and EC Level
3) EC Codewords Per Block
4) Number of Blocks in Group 1
5) Number of Data Codewords in Each of Group 1's Blocks
6) Number of Blocks in Group 2
7) Number of Data Codewords in Each of Group 2's Blocks
8) Total Data Codewords
*/
// Recupera as definições de Correção de erro
// baseado na versao atual e correção de erro desejada
aECCW := GetECCW(::nVersion,::cErrCorr)
IF aECCW = NIL
USerException("Invalid Version or Error Correction")
Endif
nTotData := val(aECCW[2])
nErrCW := val(aECCW[3])
nBlocks1 := val(aECCW[4])
nData1 := val(aECCW[5])
nBlocks2 := val(aECCW[6])
nData2 := val(aECCW[7])
// Informa o total de CodeWords de correção de erro necessários
::oLogger:Write("BUILDDATA","Total Data CodeWords ......... "+cValToChar(nTotData))
::oLogger:Write("BUILDDATA","Total Blocks Type 1 .......... "+cValToChar(nBlocks1))
::oLogger:Write("BUILDDATA","CodeWords per Block 1......... "+cValToChar(nData1))
::oLogger:Write("BUILDDATA","Total Blocks Type 2 .......... "+cValToChar(nBlocks2))
::oLogger:Write("BUILDDATA","CodeWords per Block 2......... "+cValToChar(nData2))
nReqBits := nTotData*8
::oLogger:Write("BUILDDATA","Data Required Bits ........... "+cValToChar(nReqBits))
If nBitSize < nReqBits
::oLogger:Write("BUILDDATA","Add 0000 Data Bits Terminator")
cDataBits += '0000'
Endif
// Break Data int 8 bytes blocks
aBitsBlk := {}
cBitsRow := ''
while !empty(cDataBits)
cBitsRow += left(cDataBits,1)
cDataBits := substr(cDataBits,2)
If len(cBitsRow) == 8
aadd(aBitsBlk,cBitsRow)
::oLogger:Write("BUILDDATA","Build CodeWord #"+cValToChar(len(aBitsBlk))+" ["+cBitsRow+"] ")
cBitsRow := ''
Endif
Enddo
// Complementa a sequencia de bits em multiplos de 8
IF !empty(cBitsRow)
cBitsRow := left(cBitsRow+"00000000",8)
aadd(aBitsBlk,cBitsRow)
::oLogger:Write("BUILDDATA","Padding Last CodeWord #"+cValToChar(len(aBitsBlk))+" ["+cBitsRow+"] ")
Endif
// Preenche os blocos finais ( caso vazios )
// com um padrao de preenchimento ( filler )
While len(aBitsBlk) < nTotData
If len(aBitsBlk) < nTotData
aadd(aBitsBlk,"11101100")
::oLogger:Write("BUILDDATA","Filler CodeWord #"+cValToChar(len(aBitsBlk))+" ["+"11101100"+"] ")
Endif
If len(aBitsBlk) < nTotData
aadd(aBitsBlk,"00010001")
::oLogger:Write("BUILDDATA","Filler CodeWord #"+cValToChar(len(aBitsBlk))+" ["+"00010001"+"] ")
Endif
Enddo
// Inicializa o array de inteiros que vai guardar a mensagem
// ou CodeWords da Mensagem
::oLogger:Write("BUILDDATA",padc(" Build Message CodeWord ",79,'-'))
aQRIntData := {}
cTmpCode := ''
conout("")
For nI := 1 to nTotData
BIT8TON( aBitsBlk[nI] , nInt )
::oLogger:Write("BUILDDATA","CodeWord ["+str(nI,3)+"] Data ["+aBitsBlk[nI]+"] ("+cValToChar(nInt)+")")
aadd( aQRIntData , nInt )
IF nI>1
cTmpCode += ','
Endif
cTmpCode += cValToChar(nInt)
Next
::oLogger:Write("BUILDDATA","Message Data .... "+cTmpCode)
::oLogger:Write("BUILDDATA","Error Correction CodeWords ... "+cValToChar(nErrCW))
// Distribuição em blocos e cálculo da
// correção de erro por blocos
If nBlocks1 + nBlocks2 > 1
// passo 1 . Distribuir os dados N blocos, em grupos 1 e 2
aGrupos := {{},{}}
aErrors := {{},{}}
nPosData := 1
// Blocos tipo 1
For nB := 1 to nBlocks1
// Separa os dados para o grupo
aGrpData := {}
For nI := 1 to nData1
aadd(aGrpData , aQrIntData[nPosData])
nPosData++
Next
aadd(aGrupos[1],aGrpData)
// Calcula correção de erro para o grupo
aErrData := ::BuildErrData(aGrpData,nErrCW)
aadd(aErrors[1] , aErrData )
Next
// Blocos tipo 2
For nB := 1 to nBlocks2
// Separa os dados para o grupo
aGrpData := {}
For nI := 1 to nData2
aadd(aGrpData , aQrIntData[nPosData])
nPosData++
Next
aadd(aGrupos[2],aGrpData)
// Calcula correção de erro para o grupo
aErrData := ::BuildErrData(aGrpData,nErrCW)
aadd(aErrors[1] , aErrData )