Generate QR Code with CIQRCodeDescriptor initWithPayload: symbolVersion: maskPattern errorCorrectionLevel: - qr-code

I am trying to generate a QR Code using CoreImage.
I want to be able to control the symbol version, the masking pattern, and the error correction level.
Using the simple "CIFilter filterWithName:" does not give you the ability to set the symbol version or the mask pattern.
The only way it seems possible is to use a CIQRCodeDescriptor - using "CIQRCodeDesciptor initWithPayload: symbolVersion: maskPattern: errorCorrectionLevel:"
Has anyone been able to use this method to successfully generate a QR Code image?
If so, can you please post a simple complete example?

To be able to use CIQRCodeDescriptor you need
codewords (mode + character count + data + terminator + padding)
correct symbol version (version for the character count; 1-40)
correct mask pattern (mask with minimum penalty; 0-7)
Follows example of "Think Different".
Notice the extra bits in codeword
Think Different: 54 68 69 6E 6B 20 44 69 66 66 65 72 65 6E 74
Codeword: 40 F5 46 86 96 E6 B2 04 46 96 66 66 57 26 56 E7 40 EC 11
The codeword construction is explained at nayuiki or at the bottom.
let codeword : [UInt8] = [0x40, 0xf5, 0x46, 0x86, 0x96, 0xe6, 0xb2, 0x04, 0x46, 0x96, 0x66, 0x66, 0x57, 0x26, 0x56, 0xe7, 0x40, 0xec, 0x11]
let data = Data(bytes: codeword, count: codeword.count)
if let descriptor = CIQRCodeDescriptor(payload: data, symbolVersion: 1, maskPattern: 4, errorCorrectionLevel: .levelL) {
if let image = imageFromBarcodeCodeDescriptor(descriptor)?.transformed(by: .init(scaleX: 10, y: 10)) {
let newImage = NSImage()
newImage.addRepresentation(NSCIImageRep(ciImage: image))
imageView1.image = newImage
}
}
func imageFromBarcodeCodeDescriptor(_ descriptor: CIBarcodeDescriptor) -> CIImage? {
let filter = CIFilter(name: "CIBarcodeGenerator", parameters: ["inputBarcodeDescriptor" : descriptor])
return filter?.outputImage
}
Concatenate segments, add padding, make codewords
Notes:
The segment mode is always a 4-bit field.
The character count’s field width depends on the mode and version.
The terminator is normally four “0” bits, but fewer if the data
codeword capacity is reached.
The bit padding is between zero to seven “0” bits, to fill all unused
bits in the last byte.
The byte padding consists of alternating (hexadecimal) EC and 11 until
the capacity is reached.
The entire sequence of data bits:
01000000111101010100011010000110100101101110011010110010000001000100011010010110011001100110011001010111001001100101011011100111010000001110110000010001
The entire sequence of data codeword bytes (by splitting the bit
string into groups of 8 bits), displayed in hexadecimal: 40 F5 46 86
96 E6 B2 04 46 96 66 66 57 26 56 E7 40 EC 11

It seems CIQRCodeGenerator doesn't support those parameters.
Maybe you can find what you are looking for in this library.

You need to use "CIBarcodeGenerator" CIFilter with the CIQRCodeDescriptor as input:
let data = ... // error corrected payload data
if let barcode = CIQRCodeDescriptor(payload: data,
symbolVersion: 1, // 1...40
maskPattern: 0, // 0..7
errorCorrectionLevel: .levelL) // Any of the available enum values
{
let filter = CIFilter(name: "CIBarcodeGenerator",
parameters: ["inputBarcodeDescriptor": barcode])
let image = filter?.outputImage
}
The caveat though is that you need to obtain somehow the errorCorrectedPayload data for the message you are trying to encode. One of the ways to do this would be to use "CIQRCodeGenerator" to encode the message, parse the resulting image with Vision to extract the barcode descriptor from it, and then get the errorCorrectedPayload data from that descriptor.

A simple working example is:
// Create the CIFilter (CIQRCodeGenerator)
CIFilter *ciFilter = [CIFilter filterWithName:#"CIQRCodeGenerator"];
[ciFilter setDefaults];
NSData *data = [#"123456" dataUsingEncoding:NSUTF8StringEncoding];// QR code value
[ciFilter setValue:data forKey:#"inputMessage"];
[ciFilter setValue:#"L" forKey:#"inputCorrectionLevel"];// L: low, M: Medium, Q: Quartile, H: High
// Create the image at the desired size
CGSize size = CGSizeMake(280, 280);// Desired QR code size
CGRect rect = CGRectIntegral(ciFilter.outputImage.extent);
CIImage *ciImage = [ciFilter.outputImage imageByApplyingTransform:CGAffineTransformMakeScale(size.width/CGRectGetWidth(rect), size.height/CGRectGetHeight(rect))];
// Create a UIImage (if needed)
UIImage *image = [UIImage imageWithCIImage:ciImage];
_imageView.image = image;

Related

Using R to decrypt messages encrypted in PHP

my brain hurts, I can't figure it out, I would be tremendously thankful for your help. I have a database that gets encrypted at storage using PHP. I need to decrypt it in R. I feel like I am close, but I just can't get there.
Here's the PHP code used to encrypt:
<?php
function str_encryptaesgcm($plaintext, $password) {
$iv = "1234567890123456";
$ciphertext = openssl_encrypt(
$plaintext,
"AES-256-CBC",
hash('sha256', $password, true),
OPENSSL_RAW_DATA,
$iv);
return base64_encode($ciphertext);
}
function str_decryptaesgcm($ciphertext, $password) {
$iv = "1234567890123456";
return openssl_decrypt(
base64_decode($ciphertext),
"AES-256-CBC",
hash('sha256', $password, true),
OPENSSL_RAW_DATA,
$iv);
}
$enc = str_encryptaesgcm("Hello, world!", "ABCDEFGHIJKLMNOPQRST");
echo $enc . " ";
$enc = "8FT21xlAENs0Q8GTDE5k0A==";
$dec = str_decryptaesgcm($enc, "ABCDEFGHIJKLMNOPQRST");
echo $dec;
Here, "8FT21xlAENs0Q8GTDE5k0A==" is the encrypted result of the "Hello, world!" message that I have in my database. If I run it through the str_decryptaesgcm function it spits out the original message. I need to decode this in R.
To replicate this process in R one needs to run the following code:
library(openssl)
x <- aes_cbc_encrypt(serialize('Hello, world!', NULL),
key = sha256(charToRaw('ABCDEFGHIJKLMNOPQRST')),
iv = charToRaw('1234567890123456'))
y <- aes_cbc_decrypt(
data = x,
key = sha256(charToRaw('ABCDEFGHIJKLMNOPQRST')),
iv = charToRaw('1234567890123456'))
unserialize(y)
with unserialize(y) spitting out the original message.
However, base64_encode(x) produces a string that is completely different from the one produced in PHP: "1y6CgaY23ap+tQVXQKGsYyZWDMGj/GxeHjyyFOnyRJufbfieRC4aJ7/9uDzRllC21Q7v+1bADtuzEfG83iakBw==".
I can get R to produce the PHP string, but I need to run the encryption differently:
x <- aes_cbc_encrypt(charToRaw('Hello, world!'),
key = sha256(charToRaw('ABCDEFGHIJKLMNOPQRST')),
iv = charToRaw('1234567890123456'))
Then, base64_encode(x) produces "8FT21xlAENs0Q8GTDE5k0A==". However, plugging this into the decoder produces garbage (note that it does decode, it doesn't throw an error) that I can't convert:
> y <- aes_cbc_decrypt(
+ data = x,
+ key = sha256(charToRaw('ABCDEFGHIJKLMNOPQRST')),
+ iv = charToRaw('1234567890123456'))
> y
[1] 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21
> unserialize(y)
Error in unserialize(y) : unknown input format
So the question is, what should I do to be able to convert "8FT21xlAENs0Q8GTDE5k0A==" back to the original message? I'd really appreciate some advice.
Yes, you were incredibly close. If you look carefully at y:
y
#> [1] 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21
You will see these are the ascii values of your original message as a raw vector. So you need only do:
rawToChar(y)
#> [1] "Hello, world!"

Read SerialPort RealTime in HighSpeed Mode

I work on serial Port to read data. serial port's baud-rate is 921600 bps and i use these code to read data:
while(true)
{
bytesToRead = sensor.BytesToRead;
if (bytesToRead > 0)
{
byte[] input = new byte[bytesToRead];
sensor.Read(input, 0, bytesToRead);
}
}
sending protocols is like this. (five digit numbers in bytes + \n\r )
48 48 49 52 50 10 13 , ....
that means : "00142\n\r" -> 00142 -> 142
in each loop I read 4096 bytes of data and i looking for fast way to read all numbers in buffer. i use readLine() function also but it is too slow and some data has been lost.
is there any idea what shroud i do?
thanks.

Usage of the pipe " | " in a less calculation [duplicate]

we can do the following to convert:
var a = "129.13"|0, // becomes 129
var b = 11.12|0; // becomes 11
var c = "112"|0; // becomes 112
This seem to work but not sure if this is a standard JS feature. Does any one have any idea if this is safe to use for converting strings and decimals to integers ?
Yes, it is standard behavior. Bitwise operators only operate on integers, so they convert whatever number they're give to signed 32 bit integer.
This means that the max range is that of signed 32 bit integer minus 1, which is 2147483647.
(Math.pow(2, 32) / 2 - 1)|0; // 2147483647
(Math.pow(2, 32) / 2)|0; // -2147483648 (wrong result)

understanding checksum of ascii string

I am reading a manual on sending commands via serial to a device as shown:
Assume that my equipment address is 000. I would send a command like:
">000P**cr".
what would **, my checksum be? According to the manual, I need the last two digits of the total char code of "000P".
Isn't that just the hex value of "P"? I can't seem to understand this.
Yes it's a bit confused, but my guess would be:
total = ascii('0') + ascii('0') + ascii('0') + ascii('P')
total = 48 + 48 + 48 + 80
total = 224
cksum = last2digits(total) = 24
If it does not work as is, maybe try in hexadecimal notation:
hex(total) = E0
hex_cksum = last2digits(hex(total)) = E0

Speeding up AVR function pointers

I have a program for avr where I would like to use a pointer to a method. But why is using function pointer over normal call almost 4 times slower?? And how do I speed it up?
I have:
void simple_call(){ PORTB |= _BV(1); }
void (*simple)() = &simple_call;
Then if I compile with -O3 and call:
simple_call()
it takes 250ns to complete. If I instead call:
simple()
it takes 960ns to complete!!
How can I make it faster?
why is it slower??
You see a 710 ns increase in time. For a 16 MHz clock, that time is 11 ticks.
It is not really fair to say 4X because the time increase is a constant overhead for the function pointer. In your case, the function body is tiny, so the overhead is relatively large. But if you had a case where the function was large and took 1 ms to execute, the time increase would still be 710 ns and you would be asking why does the function pointer take 0.07% longer?
To see why one approach is faster than another, you need to get at the assembler code. Using build tools such as Eclipse allows you the get an assembler listing from the GCC compiler by adding command line options not available with the Arduino IDE. This is invaluable to figure out what is going on.
Here is a section of the assembler listing showing what you think is going on:
simple_call();
308: 0e 94 32 01 call 0x264 ; 0x264 <_Z11simple_callv>
simple();
30c: e0 91 0a 02 lds r30, 0x020A
310: f0 91 0b 02 lds r31, 0x020B
314: 19 95 eicall
These listings show the source code and assembler produced by the compiler. To make sense of that and figure out timing, you need the Atmel AVR instruction reference which contains descriptions of every instruction and the number of clock ticks they take. The simple_call() is maybe what you expect and takes 4 ticks. The simple() says:
LDS = load address byte - 2 ticks
LDS = load address byte - 2 ticks
EICALL = indirect call to address loaded - 4 ticks
Those both call the function simple_call():
void simple_call(){ PORTB |= _BV(1); }
264: df 93 push r29
266: cf 93 push r28
268: cd b7 in r28, 0x3d ; 61
26a: de b7 in r29, 0x3e ; 62
26c: a5 e2 ldi r26, 0x25 ; 37
26e: b0 e0 ldi r27, 0x00 ; 0
270: e5 e2 ldi r30, 0x25 ; 37
272: f0 e0 ldi r31, 0x00 ; 0
274: 80 81 ld r24, Z
276: 82 60 ori r24, 0x02 ; 2
278: 8c 93 st X, r24
27a: cf 91 pop r28
27c: df 91 pop r29
27e: 08 95 ret
So the function pointer should take just 4 more ticks and be small compared to all the instructions in the function method.
Above, I said should and what you think is going on. I lied a bit: the assembler above is for no optimizations.
You used the optimization -O3 which changes everything.
With the optimizations, the function body gets squashed to almost nothing:
void simple_call(){ PORTB |= _BV(1); }
264: 29 9a sbi 0x05, 1 ; 5
266: 08 95 ret
That is 2 + 4 ticks. The compiler gurus have coded the compiler to figure out a much better way to execute the one line of C++. But wait there is more. When you "call" your function the compiler says "why do that? it is just one assembler instruction". The compiler decides your call is pointless and puts the instructions inline:
void simple_call(){ PORTB |= _BV(1); }
2d6: 29 9a sbi 0x05, 1 ; 5
But with the optimizations, the function pointer call remains a call:
simple();
2d8: e0 91 0a 02 lds r30, 0x020A
2dc: f0 91 0b 02 lds r31, 0x020B
2e0: 19 95 eicall
So lets see if the math adds up. With the inline, the "call" is 3 ticks. The indirect call is 8 + 6 = 14. The difference is 11 ticks! (I can add!)
So that is **why*.
how do I speed it up?
You don't need to: It is only 4 clock ticks more to make a function pointer call. Except for the most trivial functions, it does not matter.
You can't: Even if you try to inline the functions, you still need a conditional branch. A bunch of load, compare, and conditional jumps will take more than the indirect call. In other words, the function pointer is a better method of branching than any conditional.

Resources