Unable to read AT Command Response - decode

I test some basic AT Command in Hyperterminal. The GSM modem response as per my command too. But problem is that it shows me the unreadable text. I use the following code :
AT
OK
AT+CUSD=1,"*247#",15
OK
+CUSD: 1,"0062004B006100730068000A00310020004D0032004D0020005400720061006E007300
6600650072000A0032002000440069007300620075007200730065000A00330020004D0079002000
62004B006100730068000A0034002000480065006C0070006C0069006E0065000A",72
AT+CUSD=1,"1",15
OK
AT+CUSD=1,"*247#",15 command should display
Menu 1
Menu 2
Menu 3
Something like that. But it displayed the hexadecimal code which it unreadable. How can I get plain text ? Can anyone help Me ?

Judging by information provided. Where when you send the +CUSD request with DCS (Data Coding Scheme) of 15. And the response from the Bkash service with DCS of 72. It looks like your modem does not support the encoding specified in the DCS from Bkash.
I found is fairly similar question and solution to this question. Try and ensure that +CSCS is set to something like IRA or GSM and see what happens then with your +CUSD responses.

Use the following functions to decode "UCS2" response data:
public static String HexStr2UnicodeStr(String strHex)
{
byte[] ba = Hex2ByteArray(strHex);
return HexBytes2UnicodeStr(ba);
}
public static String HexBytes2UnicodeStr(byte[] ba)
{
var strMessage = Encoding.BigEndianUnicode.GetString(ba, 0, ba.Length);
return strMessage;
}
for example:
String str2 = SmsEngine.HexStr2UnicodeStr("0062004B006100730068000A00310020004D0032004D0020005400720061006E0073006600650072000A0032002000440069007300620075007200730065000A00330020004D007900200062004B006100730068000A0034002000480065006C0070006C0069006E0065000A");
// str2 = "bKash\n1 M2M Transfer\n2 Disburse\n3 My bKash\n4 Helpline\n"
Please also check UnicodeStr2HexStr()

Hi this code is something called PDU (Protocol Data Unit). To decode it is not straight forward. you need to understand the structure first.

Related

kamailio: how to get a value from SIP INVITE Header

Please help me to get the a value from SIP INVITE header reached to kamailio like INVITE sip:+341930203454#sub.domain.com;myid=+34#sub.domain.com SIP/2.0 and i want to save the myid value +34 into a variable, without the domain name.
$var(uri) = $sel(ruri);
xavp_params_explode("$(var(uri){s.unbracket})", "uri");
xlog("L_INFO", "$var(uri) Received converted to $xavp(uri=>myid[0])\n");
I tried above and it prints +34#sub.domain.com But i want to just save +34 into a variable to further check the prefix based routing from the database.
Could you please help how to get it or If there is any alternate/single line approach to get this value, please help.
thanks in advance.
An one line statement variant can be:
$var(result) = $(ru{uri.param,myid}{s.select,0,#});
Where:
$ru - is the request URI (sip address in the first line of request)
{uri.param,myid} - is a transformation returning the value of a parameter (myid in this case) in a URI
{s.select,0,#} - is a transformation returning first token from a string by splitting it using the delimiter #
I think something like this will work:
$var(uri) = $sel(ruri);
$var(myid-param) = $(var(uri){param.value,myid}); # this should return +34#sub.domain.com
$var(sip-myid-param) = "sip:" + $var(myid-param); # this should return sip:+34#sub.domain.com
$var(user-part) = $(var(sip-myid-param){uri.user}); # this should return +34
All above string operation is possible to put in one line, I used several lines just to show it in simple way.
In one line it should be something like below, but please do not quote me on this, but I hope you can get an idea
$var(user-part) = $(var("sip:" + $var($(var(uri){param.value,myid}))){uri.user});

.Net Core 3 Preview SequenceReader Length Delimited Parsing

I'm trying to use SequenceReader<T> in .Net Core Preview 8 to parse Guacamole Protocol network traffic.
The traffic might look as follows:
5.error,14.some text here,1.0;
This is a single error instruction. There are 3 fields:
OpCode = error
Reason = some text here
Status = 0 (see Status Codes)
The fields are comma delimited (semi-colon terminated), but they also have the length prefixed on each field. I presume that's so that you could parse something like:
5.error,24.some, text, with, commas,1.0;
To produce Reason = some, text, with, commas.
Simple comma delimited parsing is simple enough to do (with or without SequenceReader). However, to utilise the length I've tried the following:
public static bool TryGetNextElement(this ref SerializationContext context, out ReadOnlySequence<byte> element)
{
element = default;
var start = context.Reader.Position;
if (!context.Reader.TryReadTo(out ReadOnlySequence<byte> lengthSlice, Utf8Bytes.Period, advancePastDelimiter: true))
return false;
if (!lengthSlice.TryGetInt(out var length))
return false;
context.Reader.Advance(length);
element = context.Reader.Sequence.Slice(start, context.Reader.Position);
return true;
}
Based on my understanding of the initial proposal, this should work, though also could be simplified I think because some of the methods in the proposal make life a bit easier than that which is available in .Net Core Preview 8.
However, the problem with this code is that the SequenceReader does not seem to Advance as I would expect. It's Position and Consumed properties remain unchanged when advancing, so the element I slice at the end is always an empty sequence.
What do I need to do in order to parse this protocol correctly?
I'm guessing that .Reader here is a property; this is important because SequenceReader<T> is a mutable struct, but every time you access .SomeProperty you are working with an isolated copy of the reader. It is fine to hide it behind a property, but you'd need to make sure you work with a local and then push back when complete, i.e.
var reader = context.Reader;
var start = reader.Position;
if (!reader.TryReadTo(out ReadOnlySequence<byte> lengthSlice,
Utf8Bytes.Period, advancePastDelimiter: true))
return false;
if (!lengthSlice.TryGetInt(out var length))
return false;
reader.Advance(length);
element = reader.Sequence.Slice(start, reader.Position);
context.Reader = reader; // update position
return true;
Note that a nice feature of this is that in the failure cases (return false), you won't have changed the state yet, because you've only been mutating your local standalone clone.
You could also consider a ref-return property for .Reader.

Set caffe net parameters via string

What I want to do is the following:
I encrypted the ".prototxt" and ".caffemodel" file, so the files are not readable and the parameters not visible. During my program I decrypt the file and store the result as a string. But now I need to set the layers in my caffe network.
Is there a method to set the caffe network layers with the parameters from my string? Same for the layers in the trained network? Something comparable with the source code below (I know this source code would not work)?
shared_ptr<Net<float> > net_;
string modelString;
string trainedString;
//Decryption stuff
net_.reset(new Net<float>(modelString, TEST));
net_->CopyTrainedLayersFrom(trainedString);
Thank you a lot.
You could initialize a NetParameter class directly using the Protocol Buffer API of the NetParameter class (you'll need to include caffe/proto/caffe.pb.h):
bool ParseFromString(const string& data);
and then use it to initialize a Net class using the following constructor:
explicit Net(const NetParameter& param, const Net* root_net = NULL);
and for copying the weights:
void CopyTrainedLayersFrom(const NetParameter& param);
It's important to note that the above method requires that the string variable contains binary-formatted protobuffer and not the text-format. While the caffemodel outputted by Caffe is already in binary format, you'll have to convert the prototxt file to binary format as well, but you could do that using the protoc command-line program combined with the --encode flag.
For a more information, I'd suggest you'll look in the Protocol-Buffer's website: https://developers.google.com/protocol-buffers/
Loading net model from text format (without converting with protoc) can be done by following:
#include <google/protobuf/text_format.h>
// [...]
NetParameter net_parameter;
bool success = google::protobuf::TextFormat::ParseFromString(model, &net_parameter);
if (success){
net_parameter.mutable_state()->set_phase(TEST);
net_.reset(new Net<float>(net_parameter));
}

NIO Http file server - connection closed prematurely

I want to create an HTTP static file server using java NIO and it works fine for small files, but seems to truncate the HTTP response for larger files (672 KB out of a 3.8 MB image is returned according to my Chrome Inspector, and my browser displays a a partially corrupted image). Is this code below incorrect?
(I know there are existing libraries for this and eventually I will use one in my project. But initially I want to implement a basic one myself to see if my project concept is feasible.)
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = keys.next();
keys.remove();
if (key.isAcceptable()) {
// New Client encountered
serverSocket.accept().configureBlocking(false)
.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
// Additional data for existing client encountered
SocketChannel selectedClient = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(548);
String requestedFile2 = getRequstedFile(key, selectedClient, buffer);
buffer.clear();
buffer.flip();
FileChannel fc = FileChannel.open(Paths.get(requestedFile2));
String string = "HTTP/1.1 200 Ok\nContent-Type: image/jpeg\nContent-Length: "
+ (Files.size(Paths.get(requestedFile2)) + "\n\n");
selectedClient.write(ByteBuffer.wrap(string.getBytes()));
while (fc.read(buffer) > -1) {
buffer.flip(); // read from the buffer
selectedClient.write(buffer);
buffer.clear();
}
selectedClient.close();
}
}
(Exception handling etc. omitted for brevity)
EDIT
I have a content-length-mismatch error message. So what is the right way to determine the HTTP response size when reading a file's contents using the NIO API?
buffer.clear();
That should be
buffer.compact();
and the loop should be
while (fc.read(buffer) > 0 || buffer.position() > 0)
You're assuming everything got written by the write.
Also you need to change the HTTP header line terminators to \r\n.
And you need to study RFC 2616 about the content length.
I guess you have to check return value from selectedClient.write(), check the SocketChannel.write() documentation:
Unless otherwise specified, a write operation will return only after writing all of the r requested bytes. Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all.
Which could be the case here. Either add another inner loop which would write to output as long as there are bytes remaining in the buffer. Or you can amend the loop according to example in ByteBuffer.compact(): http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#compact()
while (buffer.position() > 0 || fc.read(buffer) > 0) {
buffer.flip(); // read from the buffer
selectedClient.write(buffer);
buffer.compact();
}
And remember that the code supposes that selectedClient is blocking. If that wasn't the case, you would need to invoke another select() waiting on the selectedClient becoming writable...

Peculiar error with ColdFusion on BlueDragon.NET

We've got an odd issue occurring with ColdFusion on BlueDragon.NET. Asking here because of the broad experience of StackOverflow users.
Tags inside POSTed content to out BlueDragon.NET server gets removed, and we're not sure where in the stack it's getting removed. So for example if we post this data
[CORE]
Lesson_Status=Incomplete
Lesson_Location=comm_13_a02_bs_enus_t17s06v01
score=
time=00:00:56
[Core_Lesson]
<sd ac="" pc="7.0" at="1289834380459" ct="" ><t id="lo8" sc=";;" st="c" /></sd>
<sd ac='' pc='7.0' at='1289834380459' ct='' ><t id='lo8' sc=';;' st='c' /></sd>
<sd ac="" pc="7.0" at="1289834380459" ct="" ><t id="lo8" sc=";;" st="c" /></sd>
<sd ac="" pc="7.0" at="1289834380459" ct="" ><t id="lo8" sc=";;" st="c" /></sd>
<b>hello1</b>
<i>hello2</i>
<table border><td>hello3</td></table>
<sd>hello4</sd>
<sd ac="1">hello5</sd>
<t>hello6</t>
<t />
<t attr="hello8" />
<strong>hello10</strong>
<img>
><>
What we get back is this:
[CORE]
Lesson_Status=Incomplete
Lesson_Location=comm_13_a02_bs_enus_t17s06v01
score=
time=00:00:56
[Core_Lesson]
hello1
hello2
hello3
hello4
hello5
hello6
hello10
>
That is, anything that starts with < and ends with > is getting stripped or filtered and no longer appears in ColdFusion's FORM scope when it's posted.
Our server with BlueDragon JX does not suffer this problem.
If we bypass using the default FORM scope and use this code, the tag-like content appears:
<cfscript>
// get the content string of the raw HTTP headers, will include all POST content as a long querystring
RAWREQUEST = GetHttpRequestData();
// split the string on "&" character, each variable should now be separate
// note that at this point duplicate variables will get clobbered
RAWFORMFIELDS = ListToArray(RAWREQUEST.content, "&");
// We're creating a structure like "FORM", but better
BetterFORM = StructNew();
// Go over each of the raw form fields, take the key
// and add it as a key, and decode the value into the value field
// and trap the whole thing if for some reason garbage gets in there
for(i=1;i LTE ArrayLen(RAWFORMFIELDS);i = i + 1) {
temp = ListToArray(RAWFORMFIELDS[i], "=");
try {
tempkey = temp[1];
tempval = URLDecode(temp[2]);
StructInsert(BetterFORM, tempkey, tempval);
} catch(Any e) {
tempThisError = "Malformed Data: " & RAWFORMFIELDS[i];
// Log the value of tempThisError here?
// WriteOutput(tempThisError);
}
}
</cfscript>
<cfdump var="#BetterFORM#">
If we do this, and use the created BetterFORM variable, it's there, so it does not seem to be a problem with the requests being filtered at some other point in the stack. I was thinking maybe it was URLScan, but that appears not to be installed. Since BD.NET runs on .NET as the engine, perhaps there's some sanitization setting that is being used on all variables somehow?
Suggestions, ideas, etc are welcome on this issue.
I don't have a BD.NET instance handy to check, but Adobe ColdFusion has a setting in the cf administrator to strip "invalid tags". That's my best guess. Adobe CF replaces them with "invalidTag", my guess is that BD.Net just strips it silently.
It turned out to be very mundane.
We had a custom tag that did customized string replacements. On one server, it was modified to NOT replace all tags. On this server, we were using an older version that did. So the fault was not a difference between BlueDragon JX and BlueDragon.NET -- it was developer team error.

Resources