DM SerialControl Communication - serial-port

Running this script in DM results in the following error during the first execution. Subsequent executions fail on SPOpen(1,9600,1,0,8), which I think implies the serial port is open at that point, but the first execution says it is not.
What is the unexpected error that is preventing communication with the serial port?
SPOpen(1,9600,1,0,8)
SPOpen( "COM1" )
SPSendString(1, "*IDN?" )
string message
number test
message = SPReceiveString(1,8,test)
Result("Acquisition "+message+" "+test+"\n")
SPClose(1)

I can't test the serial commands myself at the moment, and the exact script code of course depends on what is on the other end of the serial connections, i.e. what is expected and what is send back. And also what timeouts/delays need to be expected and cared for.
However, I can see two immediate issues with your script:
The 'SPOpen()' command returns an ID value. You need this ID in the subsequent commands, not the port number.
Whenever the script fails (i.e. throws and error), the command to close the port is never executed and it remains open (and hence blocked). To safeguard against this, you can use a 'Try{}Catch{}' construct.
I would expect your script to look something more akin to the following:
number port = 666
number baud = 9600
number stop = 10
number parity = 0
number data = 8
number portID
try
{
portID = SPOpen( port, baud, stop, parity, data )
Result( "\n Port ("+port+") opened, Handle ID: " + portID )
Result( "\n Sending messge:" + message )
string message = "*IDN?"
SPSendString( portID, message )
Result( "\n messge send." )
// Wait for response
Result( "\n Waiting for response." )
sleep( 0.3 )
number pendingBytes = SPGetPendingBytes(portID)
Result( "\n Pending bytes:" + pendingBytes )
number maxLength = 50
number bytes_back
string reply
while( pendingBytes > 1 )
{
reply += SPReceiveString( portID, maxLength, bytes_back )
pendingBytes = SPGetPendingBytes(portID)
}
Result( "\n Reply:" + Reply )
}
catch
{
// Any thrown error end up here.
// Ensures the port will not remain open
Result( "ERROR OCCURRED.\n" )
break
}
SPClose( portID )
Result( "\n Port ("+port+") closed, using Handle ID: " + portID )
The above is untested code and will surely require some adaptation, but it should get you started. You might need some "delays" when waiting for a result and you might want to wait for specific results in a while-loop.

Related

What happens if I overwrite the pyodbc connection?

I have some function to execute queries in my database and in that functions I have pyodbc.connect().
What happens if I don't close this connection and call other function that have pyodbc.connect() again? It will ignore the function because the connection is already open?
If it works the way i'm thinking, I want to do it to prevent the connection open and close everytime a function is called
Ps: I know it is not the better way to do it, I want to know only if it works how I'm thinking
It will ignore the function because the connection is already open?
No:
import pyodbc
conn_str = (
r'DRIVER=ODBC Driver 17 for SQL Server;'
r'SERVER=(local)\SQLEXPRESS;'
r'DATABASE=myDb;'
"Trusted_Connection=yes;"
)
def get_connections(cnxn):
crsr = cnxn.cursor()
sql = (
"SELECT session_id, login_name, status "
"FROM sys.dm_exec_sessions "
"WHERE program_name = 'Python' "
)
connections = crsr.execute(sql).fetchall()
return connections
def subroutine():
cnxn = pyodbc.connect(conn_str)
return get_connections(cnxn)
cnxn = pyodbc.connect(conn_str)
print(get_connections(cnxn))
# [(56, 'GORD-HP\\Gord', 'running')]
print(subroutine())
# [(56, 'GORD-HP\\Gord', 'sleeping'), (57, 'GORD-HP\\Gord', 'running')]
print(get_connections(cnxn))
# [(56, 'GORD-HP\\Gord', 'running')]

Will websocket messages always arrive entirely, at once?

This websockets tutorial https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications has this example:
exampleSocket.onmessage = function(event) {
var f = document.getElementById("chatbox").contentDocument;
var text = "";
var msg = JSON.parse(event.data);
var time = new Date(msg.date);
var timeStr = time.toLocaleTimeString();
switch(msg.type) {
case "id":
clientID = msg.id;
setUsername();
break;
case "username":
text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>";
break;
case "message":
text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
break;
case "rejectusername":
text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>"
break;
case "userlist":
var ul = "";
for (i=0; i < msg.users.length; i++) {
ul += msg.users[i] + "<br>";
}
document.getElementById("userlistbox").innerHTML = ul;
break;
}
if (text.length) {
f.write(text);
document.getElementById("chatbox").contentWindow.scrollByPages(1);
}
};
it parses the received message from the websockets server. However, can I trust that a json, sent by the websocket server, will always arrive at once for the client? What if it arrives partially? Parsing it would break it.
Can I make this assumption even for very large json messages?
I'm asking because on a TCP stream, this wouldn't be possible. The message could arrive partially.
If there is no way to receive the message entirely at once, how could I know when to parse a JSON?
Yes, each message is received as a whole. From the RFC 6455:
1.2. Protocol Overview
After a successful handshake, clients and servers transfer data back and forth in conceptual units referred to in this specification as "messages". On the wire, a message is composed of one or more frames. The WebSocket message does not necessarily correspond to a particular network layer framing, as a fragmented message may be coalesced or split by an intermediary.
6.2. Receiving Data
If the frame comprises an unfragmented message (Section 5.4), it is said that A WebSocket Message Has Been Received with type /type/ and data /data/. If the frame is part of a fragmented message, the "Application data" of the subsequent data frames is concatenated to form the /data/. When the last fragment is received as indicated by the FIN bit (frame-fin), it is said that A WebSocket Message Has Been Received with data /data/ (comprised of the concatenation of the "Application data" of the fragments) and type /type/ (noted from the first frame of the fragmented message). Subsequent data frames MUST be interpreted as belonging to a new WebSocket message.
https://www.rfc-editor.org/rfc/rfc6455
The confusion might come from the term 'socket' which is a low-level raw OS channel that yields data in chunks. However, WebSocket is a higher level protocol.

Access last value from a SignalProducer when terminated

I have a signal producer, when it's terminated I would like to know if a value was sent, I only need the last one, seems so simple ...
let myProducer: SignalProducer<MyObject, MyError> = getMyProducer()
myProducer.on(terminated: {
// I need the last value here
// Or I need to know if value was never called
}).start()
I've tried to store the value in a local var :
let myProducer: SignalProducer<MyObject, MyError> = getMyProducer()
var myValue: MyObject?
myProducer.on(value: { value in
myValue = value
}, terminated: {
guard let value = myValue else {
// value was never called
return
}
// value was called
}).start()
But sometimes terminated is called while value has been called but myValue is still nil...
First, are you really sure that you want the terminated event?
Under normal conditions, an event stream ends with a completed event. Exceptions are failed when a failure has occurred and interrupted, when the observation was ended before the stream could complete normally (E.g. cancellation).
Second: Can your SignalProducer fail, and in the failure case, do you still want the last value sent before the failure?
If not, its as easy as using the take(last:) operator:
enum MyError: Error {
case testError
}
let (signal, input) = Signal<Int, MyError>.pipe()
let observer = Signal<Int, MyError>.Observer(
value: { print("value: \($0)") },
failed: { print("error: \($0)") },
completed: { print("completed") },
interrupted: { print("interrupted") }
)
signal
.take(last: 1)
.observe(observer)
input.send(value: 1) // Nothing printed
input.send(value: 2) // Nothing printed
input.send(value: 3) // Nothing printed
input.sendCompleted() // value 3 printed
I'm using a Signal here so I can manually send events to it just for demonstration, the same works for SignalProducer as well.
Note: If we send interrupted or a failed event, the last value 3 will not be sent because those to terminating events short circuit the normal flow.
If your SignalProducer can fail, and you still want to get the last value before the failure, you can use flatMapError to ignore the Error before the last operator:
signal
.flatMapError { _ in
return .empty
}
.take(last: 1)
.observe(observer)
my answer :
producer
.flatMapError { _ in SignalProducer<Value, NoError>.empty }
.collect()
startWithResult( { result in
case let .success(results):
done(with: results.last)
case let .failure(error):
() // should not happen as errors are flatmapped
})

How to get an error message instead of an integer in MQL5?

I am trying to get the error message using OpenCl in MQL5.
int cl_ctx;
if ( ( cl_ctx = CLContextCreate( CL_USE_ANY ) ) == INVALID_HANDLE )
{
Print( "OpenCL not found: ", GetLastError() );
float pr = 2.0 / ( period + 1.0 );
result[0] = (float)price[position] * pr + prev_value * ( 1 - pr );
Print( result[0] );
return( result[0] );
}
I am getting the message as:
OpenCL not found: 5113
Now I do not know what this 5113 means. How I can get the message in human readable format that will help me debug my program effectively?
In case your code received _LastError == 5113:
the documented human-readable explanation is this one:
ERR_OPENCL_TOO_MANY_OBJECTS 5113 Too many OpenCL objects
Next time, better present a few "surrounding" lines via a copy/paste from the MT5-log, there are more details surrounding the Runtime Error incident.
All error-code definitions and explanations are kept both in documentation and in < stderror.mqh > file since ever.
Also may re-read the online documentation aids.
Lastl, but not least, always pre-clear _LastError state with a call to ResetLastError()

Adding pcap file contents to Hash Table dynamically in lua

I am trying to read .pcap file, and aggregate number of data packets for each client(client ip here is destination address). For example, if 5 data packets have been sent to xxx.ccc.vvv.bbb, i am outputting into a file in this format:
xxx.ccc.vvv.bbb 5
This is the program i have written below:
#!/usr/bin/lua
do
numberofpkts = 0
stat = {client1 = {numberofpkts = {}}}
local file = io.open("luawrite","w")
local function init_listener()
local tap = Listener.new("wlan")
local dest_addr = Field.new("wlan.da")
local pkt_type = Field.new("wlan.fc.type")
function tap.reset()
numberofpkts = 0;
end
function tap.packet(pinfo, tvb)
client = dest_addr()
client1 = tostring(client)
type = pkt_type()
if(tostring(type) == '2') then
stat.client1.numberofpkts = stat.client1.numberofpkts+1
file:write(tostring(client1),"\t", tostring(stat.client1.numberofpkts),"\n")
end
end
end
init_listener()
end
Here, wlan.da gives the destination address. wlan.fc.type indicates that it is data packet(type = 2). I am running this using a tshark on wireless traffic.
I am getting an error:
tshark: Lua: on packet 3 Error During execution of Listener Packet Callback:
/root/statistics.lua:21: attempt to call field 'tostring' (a nil value)
tshark: Lua: on packet 12 Error During execution of Listener Packet Callback happened 2 times:
/root/statistics.lua:21: attempt to call field 'tostring' (a nil value)
Please help me how i should solve this problem. Thanks in advance!
Seems that you're trying to make the stat table a dict of statistics; if so, make sure to initialize its members correctly (by the client, whatever its value is). Maybe this helps?
do
stat = {}
local file = io.open("luawrite","w")
local function init_listener()
local tap = Listener.new("wlan")
local dest_addr = Field.new("wlan.da")
local pkt_type = Field.new("wlan.fc.type")
function tap.reset()
local client = dest_addr()
stat[client] = stat[client] or {numberofpkts = 0}
stat[client].numberofpkts = 0
end
function tap.packet(pinfo, tvb)
local client, type = dest_addr(), pkt_type()
if(tostring(type) == '2') then
stat[client] = stat[client] or {numberofpkts = 0}
stat[client].numberofpkts = stat[client].numberofpkts + 1
file:write(tostring(client),"\t", tostring(stat.client1.numberofpkts),"\n")
end
end
end
init_listener()
end

Resources