Is there any way to read lab device memory via VBA - vba

I am using Agilent 34410A DMM for bunch of measuriments. I want to get the measurement data in the device via Excel VBA on ethernet port.
I can control device but whenever read I get timeout.
Where am I wrong.
Sub digread()
Dim IOaddress As String
Dim ReplyString As String
Dim a As Variant
'These variable are neccessary to initialize the VISA COM.
'Dim ioMgr As KeysightRMLib.SRMCls
' Dim ioMgr As .FmtdIOCls
Dim ioMgr As VisaComLib.ResourceManager
Dim Instrument As VisaComLib.FormattedIO488
' The following command line provides the program with the VISA name of the
' interface that it will be communication with.
' It is currently set to use GPIB to communicate
'Ioaddress = "GPIB0::5::INSTR"
' Use the following line for LAN communication (Connect "34410A", "TCPIP1::192.168.1.37::inst0::INSTR", "34410 Digital Multimeters / 2.35")
IOaddress = "TCPIP0::192.168.1.37::5025::SOCKET"
' "TCPIP1::192.168.1.37::5025::SOCKET", "34410 Digital Multimeters / 2.35")
' use the following line instead for USB communication
' IOaddress = "USB0::2391::1799::US00000002"
' Initialize the VISA COM communication
Set ioMgr = New VisaComLib.ResourceManager
Set Instrument = New VisaComLib.FormattedIO488
Set Instrument.IO = ioMgr.Open(IOaddress, NO_LOCK, 2000)
'Instrument.IO.Timeout = 3000
Instrument.WriteString ("READ?\n")
a = Instrument.ReadString() ' here timeout occours

Related

VB 6.0 Binary Reading and Writing from VB.NET

I have a vb.net code and want to convert it in vb 6.0. But I have some difficulties. I cant find equivalent of some .net classes
Dim byteswritten As Integer
Dim fs As System.IO.FileStream
Dim r As System.IO.BinaryReader
Dim CHUNK_SIZE As Integer = 65554
fs = New System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
r = New System.IO.BinaryReader(fs)
Dim FSize As Integer = CType(fs.Length, Integer)
Dim chunk() As Byte = r.ReadBytes(CHUNK_SIZE)
While (chunk.Length > 0)
dmPutStream.Write(chunk, chunk.Length, byteswritten)
If (FSize < CHUNK_SIZE) Then
CHUNK_SIZE = FSize
chunk = r.ReadBytes(CHUNK_SIZE)
Else
chunk = r.ReadBytes(CHUNK_SIZE)
End If
End While
Well, the document can be big then we used chunk. But I dont know steps for vb 6.0
Such as what i should do for binary reading.
Without all your code for opening the write stream and closing the read and write streams, here's an example of how you can do it in VB6 using ADODB.Stream.
Under Project | References, add a reference to ADO Active X Data Objects Library. My version is 6.1, but you should be okay to just choose the latest version - depends on what version of ADO is installed on your system
Hope it helps - more info online if you want to look at all the ADODB.Stream methods and properties
Public Sub StreamData(strWriteFilename As String, filePath As String)
Const CHUNK_SIZE As Long = 65554
Dim byteswritten As Integer
Dim FSize As Long
Dim adofs As New ADODB.Stream 'Object 'System.IO.FileStream
Dim varData As Variant
' Include this here - but probably defined elsewhere
Dim dmPutStream As New ADODB.Stream
' Open Write Stream
' *** Looks like you do this elsewhere
Set dmPutStream = CreateObject("ADODB.Stream")
With dmPutStream
.Type = adTypeBinary
.Open strWriteFilename, adModeWrite
End With
' Open Read strema and start pushing data from it to the write stream
Set adofs = CreateObject("ADODB.Stream") 'New System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
With adofs
.Type = adTypeBinary
.Open
.LoadFromFile filePath
' Size of Read file - do you want this?
FSize = .Size
varData = .Read(CHUNK_SIZE)
Do While Len(varData) > 0
dmPutStream.Write varData
If Not .EOS Then
varData = .Read(CHUNK_SIZE)
End If
Loop
.Close
End With
'Save binary data To disk
dmPutStream.SaveToFile strWriteFilename, adSaveCreateOverWrite
dmPutStream.Close
End Sub
Converting VB.NET to VB6 is a bad idea, and completely unnecessary. If you need to use the VB.NET code from a VB6 application, the best thing to do would be to create a COM-visible wrapper for your .NET library, and call that wrapper from your VB6 application.
You probably CAN convert the code functionally with VB6, but there really is no point. VB.NET is a better language than VB6, use its COM capabilities to save you from writing endless sketchy VB6 code.
If you are dead set on doing this, you will need to reproduce the Stream and Reader classes functionally.
Here is the source for FileStream.cs:
http://referencesource.microsoft.com/#mscorlib/system/io/filestream.cs
And for BinaryReader:
http://referencesource.microsoft.com/#mscorlib/system/io/binaryreader.cs

Com Port doesn't work unless Hyperterminal Open and Closes Port First

So I am trying to connect to a piece of hardware. If I connect and disconnect with hyperterminal first. Then close the connection and the program. Everything works fine. If I don't I receive random characters back from the hardware. I use the same settings in hyperterminal as I do in the code.
baud=9600
parity=n
data=8
stop=1
Hardware flow controls "ON":
octs=on to=on dtr=on rts=hs
If I then disconnect the hardware and the serial port I will have the same problem again.
Is there anyway I can see how to comport is being configured after hyperterminal open and closes the port? I should note I am using a prolific serial to USB adapter.
Below is the code I use to open the com port.
Function OpenCom(PortNum As Integer, Baud As Long) As Long
Dim lpDCB As DCB
Dim ComTimeout As COMMTIMEOUTS
com$ = "COM" + Trim(Str(PortNum))
'open the communications port
hcomtemp& = CreateFile(com$, GENERIC_READ Or GENERIC_WRITE, 0, ByVal 0, OPEN_EXISTING, 0, ByVal 0)
'check for errors
If hcomtemp& < 0 Then
OpenCom = hcomtemp&
Exit Function
End If
r& = PurgeComm(hcomtemp&, 12) ' purge the comm RX and TX (RXCLEAR=0x08 and TXCLEAR=0x04)
' COMMAND LINE for "Hardware" flow control - mode com: baud=9600 parity=n data=8 stop=1 octs=on to=on dtr=on rts=hs
Build$ = "baud=" + Trim(str(Baud)) + " parity=N data=8 stop=1 octs=on to=on dtr=on rts=hs"
'build the data communications block
r& = BuildCommDCB(Build$, lpDCB)
'set the communications port's parameters with the DCB
r& = SetCommState(hcomtemp&, lpDCB)
ComTimeout.ReadIntervalTimeout = 100 'maximum time to wait between received bytes (milliseconds)
ComTimeout.ReadTotalTimeoutConstant = 1000 'maximum time to wait for receive data (milliseconds)
'set the timeouts
r& = SetCommTimeouts(hcomtemp&, ComTimeout)
'set the input buffer size to 4096 bytes and the output buffer size to 4096 bytes
r& = SetupComm(hcomtemp&, 4096, 4096)
'return the handle of the newly opened communications port
OpenCom = hcomtemp&
End Function
Please, try Advanced Serial Port Monitor -> Spy mode. http://www.aggsoft.com/serial-port-monitor.htm. It will show all actions that Hyperterminal does on the port. Then you can repeat these settings. It seems that the problem is related with the hardware flow control settings.
Below is the code I used to fix my problem. I only ever had to do it this way for one piece of equipment.
Function HandShakeBM5AS(ComPort As Integer) As Boolean
Dim Bm5ACom As Long
Dim x As Variant
Dim Path As String
comm$ = ComPort
Commands$ = "MODE COM" & comm$ & ": BAUD=9600 PARITY=N DATA=8 STOP=1 TO=ON XON=OFF ODSR=OFF OCTS=ON DTR=ON RTS=HS IDSR=OFF"
Call Shell("cmd.exe /S /C" & Commands$, vbNormalFocus)
'Shell (Commands$)
End Function
BuildCommDCB() fails if 'rts=hs' is included in the control string. This causes lpDCB to be not set correctly, and SetCommState is called with the wrong values.
You can set the RTS control flag in the lpDCB structure after calling BuildCommDCB. (I would include code but I'm not certain on the Basic syntax)

SD Card Security for Windows Mobile using VB.net

Is there a way to secure the windows mobile so that it will not accept other SD Card Storage except for the one that is registered on that device? I am thinking that it is possible if I can Get the SD Card Serial Number. How to get Serial Number of Memory Card using VB.net Mobile? I can do this in windows-based app but can't find a way in Windows-Mobile... Need help.
For Each drive As DriveInfo In My.Computer.FileSystem.Drives
If drive.IsReady = True AndAlso drive.DriveType = IO.DriveType.Removable Then
Dim fso As Scripting.FileSystemObject
Dim oDrive As Scripting.Drive
fso = CreateObject("Scripting.FileSystemObject")
oDrive = fso.GetDrive(drive.Name)
Dim serialnumber = oDrive.SerialNumber
End if
Next

IRC Client in Visual Basic

Hello I am trying to create a chat bot for my twitch channel in Visual Basic. I did some research and I found this code:
Public Class My_IRC
Private _sServer As String = String.Empty '-- IRC server name
Private _sChannel As String = String.Empty '-- the channel you want to join (prefex with #)
Private _sNickName As String = String.Empty '-- the nick name you want show up in the side bar
Private _lPort As Int32 = 6667 '-- the port to connect to. Default is 6667
Private _bInvisible As Boolean = False '-- shows up as an invisible user. Still working on this.
Private _sRealName As String = "nodibot" '-- More naming
Private _sUserName As String = "nodi_the_bot" '-- Unique name so of the IRC network has a unique handle to you regardless of the nickname.
Private _tcpclientConnection As TcpClient = Nothing '-- main connection to the IRC network.
Private _networkStream As NetworkStream = Nothing '-- break that connection down to a network stream.
Private _streamWriter As StreamWriter = Nothing '-- provide a convenient access to writing commands.
Private _streamReader As StreamReader = Nothing '-- provide a convenient access to reading commands.
Public Sub New(ByVal server As String, ByVal channel As String, ByVal nickname As String, ByVal port As Int32, ByVal invisible As Boolean)
_sServer = server
_sChannel = channel
_sNickName = nickname
_lPort = port
_bInvisible = invisible
End Sub
Public Sub Connect()
'-- IDENT explained:
'-- -- When connecting to the IRC server they will send a response to your 113 port.
'-- -- It wants your user name and a response code back. If you don't some servers
'-- -- won't let you in or will boot you. Once verified it drastically speeds up
'-- -- the connecting time.
'-- -- -- http://en.wikipedia.org/wiki/Ident
'-- Heads up - when sending a command you need to flush the writer each time. That's key.
Dim sIsInvisible As String = String.Empty
Dim sCommand As String = String.Empty '-- commands to process from the room.
'-- objects used for the IDENT response.
Dim identListener As TcpListener = Nothing
Dim identClient As TcpClient = Nothing
Dim identNetworkStream As NetworkStream = Nothing
Dim identStreamReader As StreamReader = Nothing
Dim identStreamWriter As StreamWriter = Nothing
Dim identResponseString As String = String.Empty
Try
'-- Start the main connection to the IRC server.
Console.WriteLine("**Creating Connection**")
_tcpclientConnection = New TcpClient(_sServer, _lPort)
_networkStream = _tcpclientConnection.GetStream
_streamReader = New StreamReader(_networkStream)
_streamWriter = New StreamWriter(_networkStream)
'-- Yeah, questionable if this works all the time.
If _bInvisible Then
sIsInvisible = 8
Else
sIsInvisible = 0
End If
'-- Send in your information
Console.WriteLine("**Setting up name**")
_streamWriter.WriteLine(String.Format("USER {0} {1} * :{2}", _sUserName, sIsInvisible, _sRealName))
_streamWriter.Flush()
'-- Create your nickname.
Console.WriteLine("**Setting Nickname**")
_streamWriter.WriteLine(String.Format(String.Format("NICK {0}", _sNickName)))
_streamWriter.Flush()
'-- Tell the server you want to connect to a specific room.
Console.WriteLine("**Joining Room**")
_streamWriter.WriteLine(String.Format("JOIN {0}", _sChannel))
_streamWriter.Flush()
'-- By now the IDENT should be sent to your port 113. Listen to it, grab the text,
'-- and send a response.
'-- Idents are usually #### , ####
'-- That is four digits, a space, a comma, and four more digits. You need to send
'-- this back with your user name you connected with and your system.
identListener = New TcpListener(IPAddress.Any, 113)
identListener.Start()
identClient = identListener.AcceptTcpClient
identListener.Stop()
Console.WriteLine("ident connection?")
identNetworkStream = identClient.GetStream
identStreamReader = New StreamReader(identNetworkStream)
identResponseString = identStreamReader.ReadLine
Console.WriteLine("ident got: " + identResponseString)
identStreamWriter = New StreamWriter(identNetworkStream)
'-- The general format for the IDENT response. You can use UNIX, WINDOWS VISTA, WINDOWS XP, or what ever your system is.
identStreamWriter.WriteLine(String.Format("{0} : USERID : WINDOWS 7 : {1}", identResponseString, _sUserName))
identStreamWriter.Flush()
'-- By now you should be connected to your room and visible to anyone else.
'-- If you are receiving errors they are pretty explicit and you can maneuver
'-- to debuggin them.
'--
'-- What happens here is the command processing. In an infinite loop the bot
'-- read in commands and act on them.
While True
sCommand = _streamReader.ReadLine
Console.WriteLine(sCommand)
'-- Not the best method but for the time being it works.
'--
'-- Example of a command it picks up
' :nodi123!nodi12312#ipxxx-xx.net PRIVMSG #nodi123_test :? hola!
'-- You can extend the program to better read the lines!
Dim sCommandParts(sCommand.Split(" ").Length) As String
sCommandParts = sCommand.Split(" ")
'-- Occasionally the IRC server will ping the app. If it doesn't respond in an
'-- appropriate amount of time the connection is closed.
'-- How does one respond to a ping, but with a pong! (and the hash it sends)
If sCommandParts(0) = "PING" Then
Dim sPing As String = String.Empty
For i As Int32 = 1 To sCommandParts.Length - 1
sPing += sCommandParts(i) + " "
Next
_streamWriter.WriteLine("PONG " + sPing)
_streamWriter.Flush()
Console.WriteLine("PONG " + sPing)
End If
'-- With my jank split command we want to look for specific commands sent and react to them!
'-- In theory this should be dumped to a method, but for this small tutorial you can see them here.
'-- Also any user can input this. If you want to respond to commands from you only you would
'-- have to extend the program to look for your non-bot-id in the sCommandParts(0)
If sCommandParts.Length >= 4 Then
'-- If a statement is proceeded by a question mark (the semi colon's there automatically)
'-- then repeat the rest of the string!
If sCommandParts(3).StartsWith(":?") Then
Dim sVal As String = String.Empty
Dim sOut As String = String.Empty
'-- the text might have other spaces in them so concatenate the rest of the parts
'-- because it's all text.
For i As Int32 = 3 To sCommandParts.Length - 1
sVal += sCommandParts(i)
sVal += " "
Next
'-- remove the :? part.
sVal = sVal.Substring(2, sVal.Length - 2)
'-- Trim for good measure.
sVal = sVal.Trim
'-- Send the text back out. The format is they command to send the text and the room you are in.
sOut = String.Format("PRIVMSG {0} : You said '{1}'", _sChannel, sVal)
_streamWriter.WriteLine(sOut)
_streamWriter.Flush()
End If
'-- If you don't quit the bot correctly the connection will be active until a ping/pong is failed.
'-- Even if your programming isn't running!
'-- To stop that here's a command to have the bot quit!
If sCommandParts(3).Contains(":!Q") Then
' Stop
_streamWriter.WriteLine("QUIT")
_streamWriter.Flush()
Exit Sub
End If
End If
End While
Catch ex As Exception
'-- Any exception quits the bot gracefully.
Console.WriteLine("Error in Connecting. " + ex.Message)
_streamWriter.WriteLine("QUIT")
_streamWriter.Flush()
Finally
'-- close your connections
_streamReader.Dispose()
_streamWriter.Dispose()
_networkStream.Dispose()
End Try
End Sub
End Class
and
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Public Sub Main()
Dim foo As New My_IRC("irc.freenode.net", "#nodi123_test", "nodime", 6667, False)
foo.Connect()
End Sub
But I can not succeed to connect using a password because it is simply to hard for me as a beginner. (You can either set a password or use the command /server irc.twitch.tv 6667 oauth:AUTHKEY) so my question is, is there a way to set the password in the code I posted? Or is there another stable way to use IRC in Visual Basic which allows me to set a server password? Let me know, thanks.
Your first stop should be the IRC RFC documents, RFC 1459 and 2812. From the snippet of code you provided, your IRC client does not implement the PASS message -- see section 4.1.1 of RFC 1459.
4.1.1 Password message
Command: PASS Parameters: <password>
The PASS command is used to set a 'connection password'. The
password can and must be set before any attempt to register the
connection is made. Currently this requires that clients send a PASS
command before sending the NICK/USER combination and servers must
send a PASS command before any SERVER command. The password supplied
must match the one contained in the C/N lines (for servers) or I
lines (for clients). It is possible to send multiple PASS commands
before registering but only the last one sent is used for
verification and it may not be changed once registered. Numeric
Replies:
ERR_NEEDMOREPARAMS ERR_ALREADYREGISTRED
Example:
PASS secretpasswordhere
It should be relatively easy to implement:
**Console.WriteLine("**Setting Password**")
_streamWriter.WriteLine(String.Format(String.Format("PASS {0}", whateverVariableYouChooseToHoldThePassword)))
_streamWriter.Flush()**
'-- Send in your information
Console.WriteLine("**Setting up name**")
_streamWriter.WriteLine(String.Format("USER {0} {1} * :{2}", _sUserName, sIsInvisible, _sRealName))
_streamWriter.Flush()
I'll take this opportunity to mention that I wrote an IRC library a while back that may help you, at least as a reference point for how IRC behaves. I implemented a decent portion of RFC 1459 before I lost interest. Interestingly enough, my IRC library doesn't support sending the PASS message either (although it would be similarly easy to add support).
My library could theoretically be of use to you as-is, but I don't think it's production ready, so to speak.

TCP Server in VB.NET

I am not a software programmer but I have a task to create a TCP Server (a program that is listening on its network card interfaces for incoming data streams).
I have searched on the internet and I found that I can use two methods: Socket or TCPListener class.
I have created an example for the Socket class, but I was wondering how I can test it?
If another computer in the network sends some string data to the listener computer, then the message should be displayed.
Here is the example from Microsoft that I am using for the TCP server using a Socket:
Public Shared Sub Main()
' Data buffer for incoming data.
Dim data = nothing
Dim bytes() As Byte = New [Byte](1024) {}
Dim ipAddress As IPAddress = ipAddress.Any
Dim localEndPoint As New IPEndPoint(ipAddress, 0)
Dim intI As Integer = 0
'Display the NIC interfaces from the listener
For Each ipAddress In ipHostInfo.AddressList
Console.WriteLine("The NIC are {0}", ipHostInfo.AddressList(intI))
intI += 1
Next
Console.WriteLine("You are listening on {0}",localEndPoint)
' Create a TCP/IP socket.
Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' Bind the socket to the local endpoint and
' listen for incoming connections.
Try
listener.Bind(localEndPoint)
listener.Listen(200)
Catch e As SocketException
Console.WriteLine("An application is alreading using that combination of ip adress/port", e.ErrorCode.ToString)
End Try
' Start listening for connections.
While True
Console.WriteLine("Waiting for a connection...")
' Program is suspended while waiting for an incoming connection.
Dim handler As Socket = listener.Accept()
data = Nothing
' An incoming connection needs to be processed.
While True
bytes = New Byte(1024) {}
Dim bytesRec As Integer = handler.Receive(bytes)
data += Encoding.ASCII.GetString(bytes, 0, bytesRec)
Console.WriteLine("The string captured is {0}", data)
If data.IndexOf("something") > -1 Then
Exit While
End If
End While
' Show the data on the console.
Console.WriteLine("Text received : {0}", data)
' Echo the data back to the client.
Dim msg As Byte() = Encoding.ASCII.GetBytes(data)
handler.Shutdown(SocketShutdown.Both)
handler.Close()
End While
End Sub
End Class
Am I on the right lead?
Thanks
Later Edit:
I have used that code in a Console Application created with Visual Studio and I want to check the scenario when a device is sending some string message through the network.
E.g:
I have two devices :Computer A, computer B connected through LAN
I have tried this command : telnet computerA port ( from computer B) but nothing is displayed in the TCP server running from computer A.
telnet 192.168.0.150 3232
I also made a TCP client for testing (derived from the Microsoft example):
Public Class SynchronousSocketClient
Public Shared Sub Main()
' Data buffer for incoming data.
Dim bytes(1024) As Byte
Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
Dim remoteEP As New IPEndPoint(ipAddress, 11000)
' Create a TCP/IP socket.
Dim sender As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' Connect the socket to the remote endpoint.
sender.Connect(remoteEP)
Console.WriteLine("Socket connected to {0}", _
sender.RemoteEndPoint.ToString())
' Encode the data string into a byte array.
Dim msg As Byte() = _
Encoding.ASCII.GetBytes("This is a test<EOF>")
' Send the data through the socket.
Dim bytesSent As Integer = sender.Send(msg)
' Receive the response from the remote device.
Dim bytesRec As Integer = sender.Receive(bytes)
Console.WriteLine("Echoed test = {0}", _
Encoding.ASCII.GetString(bytes, 0, bytesRec))
' Release the socket.
sender.Shutdown(SocketShutdown.Both)
sender.Close()
Console.ReadLine()
End Sub
End Class 'SynchronousSocketClient
But it does not work because of the PORT setting.
If in the TCP Server I have "Dim localEndPoint As New IPEndPoint(ipAddress, 0)" then the client crashes, but if I change the port from any (0) to 11000 for example, the client works fine.
Do you know why?
Later edit 2:
Maybe I should have started with this question: Which method is recommended for my scope - asynchronous or synchronous method?
Yes, you are on the right path.
The next thing to do is to introduce message detection since TCP is stream based and not message based like UDP. This means that TCP might decide to send two of your messages in the same packet (so that one socket.Recieve will get two messages) or that it will split up your message into two packets (thus requiring you to use two socket.Recieve to get it).
The two most common ways to create message detection is:
Create a fixed size header which includes message size
Create a delimiter which is appended to all messages.
Your "server" isn't listening on a set port, so you'll need to pay attention to the "You are listening on" message that appears. Then, from another machine on the network, telnet the.ip.add.ress port. (This may require installing "telnet client", or enabling it in the Programs and Features stuff, or whatever.)
Side note...if you actually intend for this to be a server of some sort, you'll want to decide what port you want to use, so that other computers can find your service. Most people won't be able to read your screen to figure out where to connect. :)
As for your "client"...when you connect to another computer, you don't just "pick a port" (which is what a port number of 0 means in an endpoint). You need to know what port the server uses. (Reread what i said in the previous paragraph. A program running on another computer has no idea what port to use to connect to the server -- any server could be running on any port.) You need to pick a port number for the server (say, 11000...good as any, really) rather than letting it use port 0.