GLX glXQueryVersion returns error of "wrong opcode". Unix socket connection - protocols

The connection to the X server is done with Unix sockets. I can confirm that the server has GLX extension with the following code:
const char *str_extension = "GLX";
/* X protocol requires requests to be in 4 byte units */
ssize_t len = ((strlen(str_extension + 1) + 3) & ~3;
char pad_str_extension[3 + l];
rq_q_extension_t rq = {
.opcode = X11_OPCODE_QUERY_EXTENSION,
.len = 2 + len / 4,
.len_nm = strlen(str_extension),
};
memcpy(pad_str_extension, str_extension, strlen(str_extension));
rp_q_extension_t rp;
if(write(fd, &rq, sizeof(rq)) < (ssize_t)sizeof(rq))
ERROR;
if(write(fd, cbf, 3 + l) < (3 + l))
ERROR;
if(read(fd, &rp, sizeof(rp)) < (ssize_t)sizeof(rp))
ERROR;
printf("GLX present : %u\n", rp.present);
printf("\tmajor_code : %u\n", rp.major_code);
printf("\tfirst_event : %u\n", rp.first_event);
printf("\tfirst_error : %u\n", rp.first_error);
The above outputs that extension is present and has 1.4 version. My problem is that the next request fails.
rq_gxl_q_version_t rq = {
.opcode_x11 = glx_base_opcode,
.opcode_glx = X11_OPCODE_GLX_QUERYVERSION,
.len = sizeof(rq_gxl_q_version_t) / 4,
.major_version = 1,
.m1nor_version = 4,
};
rp_glx_q_version_t rp;
if(write(fd, &rq, sizeof(rq)) < (ssize_t)sizeof(rq))
ERROR;
if(read(fd, &rp, sizeof(rp)) < (ssize_t)sizeof(rp))
ERROR;
/* status is zero here */
if(!rp.status){
x11_rp_error_t* e_rp = (x11_rp_error_t*)&rp;
This request fails with the "wrong opcode" error code. I've spend few days investigating the failure, still can't find a cuse of it.

Related

Where to retrieve audio file? -- Arduino - Photon project

I have just started with electronics, and doing a project using the Spark Photon, which is based on Arduino. The project website is here: http://hackster.io/middleca/sending-sound-over-the-internet
I uploaded the following two files (.ino and .js) to the Photon, which should then capture and transmit sound (directly I assume). I expected a test.wav would be created. However, where should I find this file so I can check if everything worked?
main.ino file:
#define MICROPHONE_PIN A5
#define AUDIO_BUFFER_MAX 8192
int audioStartIdx = 0, audioEndIdx = 0;
uint16_t audioBuffer[AUDIO_BUFFER_MAX];
uint16_t txBuffer[AUDIO_BUFFER_MAX];
// version without timers
unsigned long lastRead = micros();
char myIpAddress[24];
TCPClient audioClient;
TCPClient checkClient;
TCPServer audioServer = TCPServer(3443);
void setup() {
Serial.begin(115200);
pinMode(MICROPHONE_PIN, INPUT);
// so we know where to connect, try:
// particle get MY_DEVICE_NAME ipAddress
Spark.variable("ipAddress", myIpAddress, STRING);
IPAddress myIp = WiFi.localIP();
sprintf(myIpAddress, "%d.%d.%d.%d", myIp[0], myIp[1], myIp[2], myIp[3]);
// 1/8000th of a second is 125 microseconds
audioServer.begin();
lastRead = micros();
}
void loop() {
checkClient = audioServer.available();
if (checkClient.connected()) {
audioClient = checkClient;
}
//listen for 100ms, taking a sample every 125us,
//and then send that chunk over the network.
listenAndSend(100);
}
void listenAndSend(int delay) {
unsigned long startedListening = millis();
while ((millis() - startedListening) < delay) {
unsigned long time = micros();
if (lastRead > time) {
// time wrapped?
//lets just skip a beat for now, whatever.
lastRead = time;
}
//125 microseconds is 1/8000th of a second
if ((time - lastRead) > 125) {
lastRead = time;
readMic();
}
}
sendAudio();
}
// Callback for Timer 1
void readMic(void) {
uint16_t value = analogRead(MICROPHONE_PIN);
if (audioEndIdx >= AUDIO_BUFFER_MAX) {
audioEndIdx = 0;
}
audioBuffer[audioEndIdx++] = value;
}
void copyAudio(uint16_t *bufferPtr) {
//if end is after start, read from start->end
//if end is before start, then we wrapped, read from start->max, 0->end
int endSnapshotIdx = audioEndIdx;
bool wrapped = endSnapshotIdx < audioStartIdx;
int endIdx = (wrapped) ? AUDIO_BUFFER_MAX : endSnapshotIdx;
int c = 0;
for(int i=audioStartIdx;i<endIdx;i++) {
// do a thing
bufferPtr[c++] = audioBuffer[i];
}
if (wrapped) {
//we have extra
for(int i=0;i<endSnapshotIdx;i++) {
// do more of a thing.
bufferPtr[c++] = audioBuffer[i];
}
}
//and we're done.
audioStartIdx = audioEndIdx;
if (c < AUDIO_BUFFER_MAX) {
bufferPtr[c] = -1;
}
}
// Callback for Timer 1
void sendAudio(void) {
copyAudio(txBuffer);
int i=0;
uint16_t val = 0;
if (audioClient.connected()) {
write_socket(audioClient, txBuffer);
}
else {
while( (val = txBuffer[i++]) < 65535 ) {
Serial.print(val);
Serial.print(',');
}
Serial.println("DONE");
}
}
// an audio sample is 16bit, we need to convert it to bytes for sending over the network
void write_socket(TCPClient socket, uint16_t *buffer) {
int i=0;
uint16_t val = 0;
int tcpIdx = 0;
uint8_t tcpBuffer[1024];
while( (val = buffer[i++]) < 65535 ) {
if ((tcpIdx+1) >= 1024) {
socket.write(tcpBuffer, tcpIdx);
tcpIdx = 0;
}
tcpBuffer[tcpIdx] = val & 0xff;
tcpBuffer[tcpIdx+1] = (val >> 8);
tcpIdx += 2;
}
// any leftovers?
if (tcpIdx > 0) {
socket.write(tcpBuffer, tcpIdx);
}
}
and the waveRecorder.js file:
// make sure you have Node.js Installed!
// Get the IP address of your photon, and put it here:
// CLI command to get your photon's IP address
//
// particle get MY_DEVICE_NAME ipAddress
// Put your IP here!
var settings = {
ip: "192.168.0.54",
port: 3443
};
/**
* Created by middleca on 7/18/15.
*/
//based on a sample from here
// http://stackoverflow.com/questions/19548755/nodejs-write-binary-data-into-writablestream-with-buffer
var fs = require("fs");
var samplesLength = 1000;
var sampleRate = 8000;
var outStream = fs.createWriteStream("test.wav");
var writeHeader = function() {
var b = new Buffer(1024);
b.write('RIFF', 0);
/* file length */
b.writeUInt32LE(32 + samplesLength * 2, 4);
//b.writeUint32LE(0, 4);
b.write('WAVE', 8);
/* format chunk identifier */
b.write('fmt ', 12);
/* format chunk length */
b.writeUInt32LE(16, 16);
/* sample format (raw) */
b.writeUInt16LE(1, 20);
/* channel count */
b.writeUInt16LE(1, 22);
/* sample rate */
b.writeUInt32LE(sampleRate, 24);
/* byte rate (sample rate * block align) */
b.writeUInt32LE(sampleRate * 2, 28);
/* block align (channel count * bytes per sample) */
b.writeUInt16LE(2, 32);
/* bits per sample */
b.writeUInt16LE(16, 34);
/* data chunk identifier */
b.write('data', 36);
/* data chunk length */
//b.writeUInt32LE(40, samplesLength * 2);
b.writeUInt32LE(0, 40);
outStream.write(b.slice(0, 50));
};
writeHeader(outStream);
var net = require('net');
console.log("connecting...");
client = net.connect(settings.port, settings.ip, function () {
client.setNoDelay(true);
client.on("data", function (data) {
try {
console.log("GOT DATA");
outStream.write(data);
//outStream.flush();
console.log("got chunk of " + data.toString('hex'));
}
catch (ex) {
console.error("Er!" + ex);
}
});
});
setTimeout(function() {
console.log('recorded for 10 seconds');
client.end();
outStream.end();
process.exit(0);
}, 10 * 1000);
Thieme! Such a beginner's question... SO unworthy!
Anyway, I will iron my heart and tell you the answer.
First of all, you misunderstood: the .ino file should go to the Photon and the waveRecorder.js file should be stored on your computer (or server) and called whenever you want to retrieve the audio. As you can read in the code, the .ino file makes sure that every millisecond it will check if something wants to connect, and if so, it will stream the sound to the wav.file stored in the same location as your waveRecorder.js file. "Something wants to connect" happens when you launch waveRecorder.js. Make sure you have node installed.
So, to sum it up:
Download the two files (main.ino and waveRecorder.js) to your computer in a folder ../xx/folderName
Then configure the IPAddress in both files using your photon's IPAddress
Upload main.ino to the photon (type 'particle flash abcdefgh123456578 "xx/../folderName/main.ino"' in the terminal)
Then run waveRecorder.js by typing 'node "xx/../folderName/waveRecorder.js"' in your terminal.
That should do it.. Even I got it working :)

NodeJS is faster than D when computing prime numbers. How?

I wrote a simple function for computing prime numbers in D. I thought it was pretty quick, calculating prime numbers up to 100,000. But then I wanted to compare it to NodeJS. When I ran the NodeJS script for the first time, I was astounded at the difference and double checked I wasn't skipping some sort of calculation some how. But the two are pretty identical functionally.
D:
import std.stdio;
import std.math;
import std.datetime;
import std.file;
import std.array;
enum size_t ITERATIONS = 100_000;
bool divisible(real n) {
real d;
for(d = 3; d < floor(n / 2); d += 2) {
if(n % d == 0) {
return true;
}
}
return false;
}
void main() {
StopWatch sw;
size_t T = ITERATIONS;
size_t C = 0;
real n = 2;
real r[ITERATIONS];
r[C] = n;
sw.start();
C++;
for(n = 3; n < T; n += 2) {
if(!divisible(n)) {
r[C] = n;
C++;
}
}
sw.stop();
double seconds = cast(double)sw.peek().usecs / 1_000_000;
writeln("\n\n", C, " prime numbers calculated in ", seconds, " seconds.");
File file = File("primes.txt", "w");
file.writeln("\n", C, " prime numbers calculated ", seconds, " seconds.");
foreach(number; r[0..C]) {
file.writeln(number);
}
file.writeln("\n", "end");
file.close();
}
NodeJS:
var fs = require('fs');
var ITERATIONS = 100000;
function divisible(n) {
var d;
for(d = 3; d < Math.floor(n / 2); d += 2) {
if(n % d == 0) {
return true;
}
}
return false;
}
(function() {
var buffer = [ ],
now = Date.now(),
C = 0
n = 2
;
buffer.push(n);
C++;
for(n = 3; n < ITERATIONS; n += 2) {
if(!divisible(n)) {
buffer.push(n);
C++;
}
}
var time = Date.now() - now,
seconds = time / 1000
;
console.log("\n\n", C, " prime numbers calculated. Process took ", seconds, " seconds.");
buffer.push("\n" + C + " prime numbers calculated. Process took " + seconds + " seconds.");
fs.writeFile("node_primes.txt", buffer.join("\n"), function(err) {
if(err) throw err;
console.log("Primes have been written to file.");
});
})();
Results:
Calculating 100,000 primes:
D: 3.49126 seconds
NodeJS: 0.652 seconds
Can anybody explain why this is happening?
Thanks in advance.
By unnecessarily declaring variables as real, you are forcing floating point arithmetic where integer arithmetic could be used. Replace all instances of real with int, get rid of that floor() and your D program will run as fast as the Node.JS version:
import std.stdio;
import std.math;
import std.datetime;
import std.file;
import std.array;
enum size_t ITERATIONS = 100_000;
bool divisible(int n) {
int d;
for(d = 3; d < n / 2; d += 2) {
if(n % d == 0) {
return true;
}
}
return false;
}
void main() {
StopWatch sw;
size_t T = ITERATIONS;
size_t C = 0;
int n = 2;
int r[ITERATIONS];
r[C] = n;
sw.start();
C++;
for(n = 3; n < T; n += 2) {
if(!divisible(n)) {
r[C] = n;
C++;
}
}
sw.stop();
double seconds = cast(double)sw.peek().usecs / 1_000_000;
writeln("\n\n", C, " prime numbers calculated in ", seconds, " seconds.");
File file = File("primes.txt", "w");
file.writeln("\n", C, " prime numbers calculated ", seconds, " seconds.");
foreach(number; r[0..C]) {
file.writeln(number);
}
file.writeln("\n", "end");
file.close();
}

How to read non-byte-aligned integers with Node.js?

I am trying to read a binary SWF file using Node.JS. As the specification mentions at the bottom of the 17th page, some integers are encoded using variable-length bit fields, and by definition most of them are not byte-aligned.
The problem is that Node.js's Buffer only provides functions for reading byte-aligned integers. So I tried to write a wrapper object that would read bit by bit. However, it seems really hacky. Below is the object prototype I wrote:
/*jslint node:true, bitwise:true */
'use strict';
var util = require('util');
var maxBits = 32;
function BitBuffer() {
Buffer.apply(this, arguments);
this.cursor = 0;
this.bitCursor = 0;
}
util.inherits(BitBuffer, Buffer);
module.exports = BitBuffer;
function padBits(bits, length, bit) {
var leftPad = '', repeatLength, i;
bits = bits.toString(2);
length = length || 8;
bit = bit || '0';
if (bits.length >= length) {
return bits;
} else {
repeatLength = length - bits.length;
for (i = 0; i < repeatLength; i += 1) {
leftPad += bit;
}
return leftPad + bits;
}
}
BitBuffer.prototype.move = function (bits) {
var bytes = Math.floor((this.bitCursor + bits) / 8);
this.bitCursor += bits;
if (this.bitCursor > 8) {
this.cursor += bytes;
this.bitCursor -= bytes * 8;
}
if (this.cursor >= this.length) {
this.rewind();
return false;
}
return true;
};
BitBuffer.prototype.align = function () {
if (this.bitCursor > 0) {
this.bitCursor = 0;
this.cursor += 1;
}
};
BitBuffer.prototype.rewind = function () {
this.cursor = this.bitCursor = 0;
};
BitBuffer.prototype.readBits = function (bits) {
var bytes = Math.ceil((this.bitCursor + bits) / 8), result = 0,
length, buffer, i;
if (bits > maxBits) {
throw new RangeError('Cannot read more than ' + maxBits + ' bits');
}
buffer = this.slice(this.cursor, this.cursor + bytes);
result = padBits(buffer[0]).substr(this.bitCursor);
length = buffer.length;
for (i = 1; i < length; i += 1) {
result += padBits(buffer[i]);
}
result = result.substr(0, bits);
return (this.move(bits)) ? parseInt(result, 2) : false;
};
BitBuffer.prototype.readUB = BitBuffer.prototype.readBits;
BitBuffer.prototype.readSB = function (bits) {
var readBits = this.readBits(bits),
stringBits = readBits.toString(2);
if (readBits === false) {
return false;
}
// add automatically removed zeros
if (stringBits.length < bits) {
stringBits = padBits(stringBits, bits);
}
// negative, pad to 32 bits then invert bits
if (stringBits[0] === '1') {
return -~parseInt(padBits(stringBits, maxBits, '1'), 2) - 1;
} else {
return readBits;
}
};
BitBuffer.prototype.readFB = function (bits) {
var highBits, lowBits, result;
if (bits < 17) {
throw new RangeError('Should be at least 17 bits long');
}
highBits = this.readSB(bits - 16);
lowBits = this.readUB(16);
lowBits *= Math.pow(10, -lowBits.toString(10).length);
return (highBits >= 0) ?
highBits + lowBits : highBits - lowBits;
};
// wrap read functions
(function () {
var nativeReadFunctions = {
'readInt8': 8,
'readInt16LE': 16,
'readInt16BE': 16,
'readInt32LE': 32,
'readInt32BE': 32,
'readUInt8': 8,
'readUInt16LE': 16,
'readUInt16BE': 16,
'readUInt32LE': 32,
'readUInt32BE': 32,
'readDoubleLE': 64,
'readDoubleBE': 64,
'readFloatLE': 32,
'readFloatBE': 32
}, method;
function wrapNativeRead(method, length) {
return function (noAssert) {
var cursor;
this.align();
cursor = this.cursor;
this.move(length);
return Buffer.prototype[method].call(
this,
this.cursor,
noAssert
);
};
}
for (method in nativeReadFunctions) {
if (nativeReadFunctions.hasOwnProperty(method)) {
BitBuffer.prototype[method] =
wrapNativeRead(method, nativeReadFunctions[method]);
}
}
}());
Is writing my own object the good way?
Beside your implementation is pretty good, you should understand that in your implementation this.buffer === this and you should change the following lines:
// inside BitBuffer prototype constructor
this.buffer = new Buffer(param1, param2);
// change to
Buffer.call(this, param1, param2); // The right way to call the super constructor
and
// inside BitBuffer.prototype.readBits
buffer = this.buffer.slice(this.cursor, this.cursor + bytes);
// change to
buffer = this.slice(this.cursor, this.cursor + bytes);

Smart card write error

i am working in smart card development. i have created MF (Master file), DF (dedicated File), EF (Elementary file) in smart card. EF file is used to store the data. This EF may be transparent file or record oriented file. i have written the data to transparent file using 00D1000008 540100 5303 010203 this command.i am also try to write the record oriented file using 00DD000008 540100 5303 010203 this command. but i got the error (6700 error code) wrong length. i need the solution to write the smart card EF record oriented file. please guide me.
Screen shot:
My code:
i have used winscard.dll
private void button_Transmit_Click(object sender, EventArgs e)
{
Status.Text = "";
byte[] baData = null;
string sClass = textBox_Class.Text;
string sIns = textBox_CLA.Text;
string sP1 = textBox_P1.Text;
string sP2 = textBox_P2.Text;
string sP3 = textBox_P3.Text;
sP3 = sP3.ToUpper();
int k1 = 70;
string sData = textBox1.Text;
byte bP1 = 0;
byte bP2 = 0;
byte bP3 = 0;
byte bClass = byte.Parse(sClass, NumberStyles.AllowHexSpecifier);
byte bIns = byte.Parse(sIns, NumberStyles.AllowHexSpecifier);
if (sP1 != "" && sP1 != "#")
bP1 = byte.Parse(sP1, NumberStyles.AllowHexSpecifier);
if (sP2 != "" && sP2 != "#")
bP2 = byte.Parse(sP2, NumberStyles.AllowHexSpecifier);
int integer = int.Parse(sP3, NumberStyles.AllowHexSpecifier);
byte bLe = (byte)k1;
if (integer != 0 && sData.Length != 0)
{
baData = new byte[integer];
for (int nJ = 0; nJ < sData.Length; nJ += 2)
baData[nJ / 2] = byte.Parse(sData.Substring(nJ, 2), NumberStyles.AllowHexSpecifier);
bLe = 0;
}
UInt32 m_nProtocol = (uint)PROTOCOL.Undefined;
uint RecvLength = 0;
byte[] ApduBuffer = null;
IntPtr ApduResponse = IntPtr.Zero;
SCard_IO_Request ioRequest = new SCard_IO_Request();
ioRequest.m_dwProtocol = m_nProtocol;
ioRequest.m_cbPciLength = 8;
if (baData == null)
{
ApduBuffer = new byte[4 + ((bLe != 0) ? 1 : 0)];
if (bLe != 0)
{
ApduBuffer[4] = (byte)bLe;
}
}
else
{
if (textBox1.Text.Length > 8)
{
ApduBuffer = new byte[5 + baData.Length];
Buffer.BlockCopy(baData, 0, ApduBuffer, 5, baData.Length);
ApduBuffer[4] = (byte)(baData.Length);
}
//read binary
else
{
ApduBuffer = new byte[5 + baData.Length + 1];
Buffer.BlockCopy(baData, 0, ApduBuffer, 5, baData.Length);
ApduBuffer[4] = (byte)(baData.Length);
ApduBuffer[5 + baData.Length] = 255;
}
}
ApduBuffer[0] = bClass;
ApduBuffer[1] = bIns;
ApduBuffer[2] = bP1;
ApduBuffer[3] = bP2;
m_nLastError = SCardTransmit(scard.m_hCard, ref ioRequest, ApduBuffer, (uint)ApduBuffer.Length, ref ioRequest, ApduResponse, ref RecvLength);
textBox2.Text = "";
byte[] caReadersData = new byte[RecvLength];
if (m_nLastError == 0)
{
ApduResponse = Marshal.AllocHGlobal((int)RecvLength);
if (m_nLastError == 0)
{
m_nLastError = SCardTransmit(scard.m_hCard, ref ioRequest, ApduBuffer, (uint)ApduBuffer.Length, ref ioRequest, ApduResponse, ref RecvLength);
if (RecvLength > 2)
{
for (int nI = 0; nI < RecvLength - 2; nI++)
{
caReadersData[nI] = Marshal.ReadByte(ApduResponse, nI);
//kl[nI] = Marshal.ReadByte(ApduResponse, nI);
//result = string.Format("{0:X02}", caReadersData[nI]);
//Status.Text += string.Format("{0:X02}", caReadersData[nI]) + " ";
textBox2.Text += string.Format("{0:X02}", caReadersData[nI]) + " ";
//result = Status.Text;
}
}
else
{
for (int nI = 0; nI < RecvLength; nI++)
{
caReadersData[nI] = Marshal.ReadByte(ApduResponse, nI);
Status.Text += string.Format("{0:X02}", caReadersData[nI]) + " ";
}
}
}
}
Marshal.FreeHGlobal(ApduResponse);
}
Edit:
READ COMMAND is working fine. see the screen shot
It seems that you use an undefined coding of P2 with the odd instruction UPDATE RECORD command. Also, you have to specify the record number in P1. For the three least significant bits use
100-Replace
101-Logical AND
110-Logical OR
111-Logical XOR
If you aim for writing / updating complete records of small length, you might consider using the commands with even instruction. Then you can drop the offset DO (0x54) and only transmit the complete record (value of the discretionary data DO (0x53)).

equivalent of INET_ATON() in mongodb

What is the equivalent of INET_ATON() in mongodb? I am using nodejs with mongodb so if a equivalent in nodejs is avaliable than it is good enough.
// ip example: 192.168.2.1
function inet_aton(ip){
// split into octets
var a = ip.split('.');
var buffer = new ArrayBuffer(4);
var dv = new DataView(buffer);
for(var i = 0; i < 4; i++){
dv.setUint8(i, a[i]);
}
return(dv.getUint32(0));
}
// num example: 3232236033
function inet_ntoa(num){
var nbuffer = new ArrayBuffer(4);
var ndv = new DataView(nbuffer);
ndv.setUint32(0, num);
var a = new Array();
for(var i = 0; i < 4; i++){
a[i] = ndv.getUint8(i);
}
return a.join('.');
}
http://rolfrost.de/ipjs.html
Here's someone else's solution for converting an IP address from a dotted-decimal string to a 32-bit number:
function dot2num(dot)
{
var d = dot.split('.');
return ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]);
}
From here: IP-addresses stored as int results in overflow?
function inet_aton(ip){
var a = new Array();
a = ip.split('.');
return((a[0] << 24) >>> 0) + ((a[1] << 16) >>> 0) + ((a[2] << 8) >>> 0) + (a[3] >>> 0);
}
function inet_ntoa(n){
var a = ((n >> 24) & 0xFF) >>> 0;
var b = ((n >> 16) & 0xFF) >>> 0;
var c = ((n >> 8) & 0xFF) >>> 0;
var d = (n & 0xFF) >>> 0;
return(a + "." + b + "." + c + "." + d);
}
as of my site see below/above, compatible with older browsers.
Here's a version of the ntoa function in Javascript using typed arrays.
function ntoa(ipInt) {
var buffer = new ArrayBuffer(4);
var uint8View = new Uint8Array(buffer);
var uint32View = new Uint32Array(buffer);
uint32View[0] = ipInt;
var ipSegments = [];
for (var i = 0; i < uint8View.length; i ++) {
ipSegments.push(uint8View[i]);
}
return ipSegments.join(".");
}

Resources