|
byte[] bytesToSend={0xA0, 0x04, 0x01, 0x89, 0x01,0xD1}; // command to send to device
mySerialPort.Write( bytesToSend,0,bytesToSend.Length); //writing to serial port
System.Threading.Thread.Sleep(200);
int count=mySerialPort.BytesToRead; //counting the bytes of response command
System.Console.WriteLine(count);
mySerialPort.Read(name,0,count); //read data from serial port
System.Console.WriteLine(Convert.ToBase64String(name)); //write data to console
Now i am having issue that my response command have 12 bytes and bytesToRead is giving 12 ..but i am not getting the exact response command/data .I am getting garbage value .what should i have to do ??
|
|
|
|
|
Start by using Hyperterminal or similar to check that you are communicating with the right device, on the right port, at the right communications settings. When you have that working fine, then transfer those details to you app and start establishing communications - but until you know that everything is working fine first, you have far too many variables to even start debugging comms in your own software. And using Thread.Sleep is not a good idea: the other device may or may not respond completely in that time - it's a better idea to use the SerialPort.DataReceived event to "build up" the response data instead of expecting comms to happen in a fixed timeframe.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
yes i already used Termite .The issue has been resolved .Thank you
|
|
|
|
|
mySerialPort.Read(name,0,count);
The "Read" returns the number of bytes actually read (which you don't check).
You need to compare the "BytesToRead" with the number actually retrieved, and do another "Read" if all the bytes have not yet been returned (it happens).
Yes; you can use the "received" event to "receive" data asynchronously; in all my "cases" however, it never worked properly and I did my own "reading" and "timeouts". And trying to access a "single" resource like a com port asynchronously for multiple "clients" is a difficult proposition.
The "sleep" is not a problem; particularly if the device being queried requires "settling time" (like a scale).
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
without sleep ,it is not writing proper command to serial port. the issue has been resolved .thank you
|
|
|
|
|
Why do you use Convert.ToBase64String(name) ?
I am pretty sure that that's the line producing the garbage you see. I'd try System.Text.Encoding.ASCII.GetString() instead. But of course, a different encoding could be required depending on the specification of the sender.
|
|
|
|
|
yes you are right .when i used
BitConverter.ToString(data); .i got my required response. Thank you
|
|
|
|
|
my video/audio/text application give this exception specially when i allow video call.
project is tcp/ip base , allow video in picturebox by directx capture and for audio is NAudio.
butwhen i allow user to communicate with video also give above exception . i dont know why? plz help.
private void button_PuchVideo_Click(object sender, EventArgs e)
{
lblVCleint1.Visible = true;
lblVCleint2.Visible = true;
pictureBox.Visible = true;
pictureBox_Remote.Visible = true;
try
{
if (capture != null)
{
if (capture.PreviewWindow != panelVideo)
{
capture.PreviewWindow = panelVideo;
}
capture.FrameEvent2 += new Capture.HeFrame(CaptureDone);
capture.GrapImg();
PeerIP_TXT.Enabled = false;
button_PuchVideo.Enabled = false;
isSending = true;
}
}
catch (Exception) { }
}
void server()
{
try
{
server_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server_sock.Bind(new IPEndPoint(IPAddress.Any, 6000));
server_sock.Listen(-1);
while (true)
{
try
{
Socket new_socket = server_sock.Accept();
NetworkStream ns = new NetworkStream(new_socket);
pictureBox_Remote.Image = Image.FromStream(ns);
ns.Close();
new_socket.Close();
}
catch (Exception)
{
}
}
}
catch (Exception) { }
}
void SendVideoBuffer(object bufferIn)
{
try
{
TcpClient tcp = new TcpClient(PeerIP_TXT.Text, 6000);
NetworkStream ns = tcp.GetStream();
Image buffer = (Image)bufferIn;
lock(buffer)
buffer.Save(ns, System.Drawing.Imaging.ImageFormat.Jpeg);
ns.Close();
tcp.Close();
}
catch (Exception) { }
}
bool isSending = false;
private void CaptureDone(System.Drawing.Bitmap e)
{
try
{
this.pictureBox.Image = e;
if (isSending)
ThreadPool.QueueUserWorkItem(new WaitCallback(SendVideoBuffer), pictureBox.Image);
}
catch (Exception) { }
}
|
|
|
|
|
The exception will have a stack trace. This will tell you the exact line in your code that has threw the exception. It's a simple case of putting a breakpoint in your code and inspecting the value when you run through. The one that is null is the one that's causing you a problem.
This space for rent
|
|
|
|
|
I've just had a quick scan of your code. I would recommend that you move away from the idea of repeatedly opening and closing connections. These can end up being expensive operations and it is possible to starve your application of resources if you aren't careful.
This space for rent
|
|
|
|
|
Exception Details: System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b9a188c8922137c6' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b9a188c8922137c6' could not be loaded.
=== Pre-bind state information ===
LOG: DisplayName = Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b9a188c8922137c6
(Fully-specified)
LOG: Appbase = file:///D:/MOJT/DAE_PIMS_New/Dae_PIMS/
LOG: Initial PrivatePath = D:\MOJT\DAE_PIMS_New\Dae_PIMS\bin
Calling assembly : Ext.Net, Version=1.2.0.24218, Culture=neutral, PublicKeyToken=2e12ce3d0176cd87.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: D:\MOJT\DAE_PIMS_New\Dae_PIMS\web.config
LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b9a188c8922137c6
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/mojt/7748f75a/267903e8/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/mojt/7748f75a/267903e8/Newtonsoft.Json/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///D:/MOJT/DAE_PIMS_New/Dae_PIMS/bin/Newtonsoft.Json.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.
Stack Trace:
[FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b9a188c8922137c6' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type) +0
System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) +191
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) +162
System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg) +148
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +604
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimePropertyInfo property, RuntimeType caType) +114
Ext.Net.ViewStateProcessor.GetProperties(Object obj) +580
Ext.Net.ViewStateProcessor.SaveViewState(Object obj) +79
Ext.Net.XControl.SaveViewState() +214
System.Web.UI.Control.SaveViewStateRecursive(ViewStateMode inheritedMode) +103
System.Web.UI.Control.SaveViewStateRecursive(ViewStateMode inheritedMode) +398
System.Web.UI.Control.SaveViewStateRecursive(ViewStateMode inheritedMode) +398
System.Web.UI.Control.SaveViewStateRecursive(ViewStateMode inheritedMode) +398
System.Web.UI.Control.SaveViewStateRecursive(ViewStateMode inheritedMode) +398
System.Web.UI.Page.SaveAllState() +685
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +8302
|
|
|
|
|
|
fyi: System.Drawing.Color.Red has:
'IsKnownColor and 'IsNamedColor properties : 'true
Can you predict the results of the comparisons in this code ?
public void ColorChallenge()
{
int rval = Color.Red.ToArgb();
Color clr = Color.FromArgb(rval);
bool ismatchEq1 = Color.Red.Equals(clr);
bool ismatchEq2 = Color.Red == clr;
bool ismatchEq3 = rval == clr.ToArgb();
bool isknown = clr.IsKnownColor;
bool isnamed = clr.IsNamedColor;
} And for extra dollops of delicious pro-social goodness, predict the Type of the variable 'hx stored in 'hxtype:
public void ColorChallenge2()
{
int rval = Color.Red.ToArgb();
string hex = $"0x{rval:X8}";
var hx = 0xFFFF0000;
string hxtype = hx.GetType().Name;
} Notice anything interesting ?
«Beauty is in the eye of the beholder, and it may be necessary from time to time to give a stupid or misinformed beholder a black eye.» Miss Piggy
modified 30-Jun-17 22:10pm.
|
|
|
|
|
BillWoodruff wrote: Can you predict the results of the comparisons in this code ? No, but I can guess. A Color would be a struct (even the "Red" property is a struct), and you are comparing that to an integer. If I "ToString" a color, I'd get a description of that color in a non-ARGB format. Makes me wonder how the comparer is implemented
BillWoodruff wrote: And for extra dollops of delicious pro-social goodness, predict the Type of the variable 'hx stored in 'hxtype: Hx would be a value-type, and I'd guess it would have to be something like a dword. ..which .NET does not have
I can predict, without trying, that the example cannot be compiled on my machine, due to the format-string syntax in the second example
--edit
Just gave it a try; var has its uses, among obfuscation. That last part works.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
modified 1-Jul-17 9:58am.
|
|
|
|
|
Eddy Vluggen wrote: you are comparing that to an integer. Nope ... only same types are compared. While both Integer and Color are structs, trying to compare them will make a compile-time error.Eddy Vluggen wrote: Hx would be a value-type, and I'd guess it would have to be something like a dword. Well, yes it's a value-type, but, it's 'uint. For details on the hack you need to use to work around that, please see my response to Harold Aptroot below.Eddy Vluggen wrote: format-string syntax in the second example [^] C# 6 string-interpolation has some very powerful facilities of particular interest if you need to deal with multiple languages/CultureInfo.
cheers, Bill
«Beauty is in the eye of the beholder, and it may be necessary from time to time to give a stupid or misinformed beholder a black eye.» Miss Piggy
|
|
|
|
|
Cool, been using that "simple" thing for a long time now; learned something new about Color
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Yep, Color is weird. A lot of it has to do with the fact that it isn't just a wrapper around int as one might as expect. At least that's what I expected when I first met System.Drawing.Color , because what else could/should it be?
Turns out it has a bunch of weird members:
private readonly string name;
private readonly long value;
private readonly short knownColor;
private readonly short state;
|
|
|
|
|
Right on Harold ! The fact that
bool colorweirdness = Color.FromArgb(Color.Red.ToArgb()) != Color.Red; results in 'true gives the game away.
And, the strange "automatic conversion" to 'uint that happens in the second "challenge" is perplexing, with the only remedy being a hack like this:'
public static int HexStringToUnchecked(string hex)
{
return unchecked(Convert.ToInt32(hex, 16));
}
«Beauty is in the eye of the beholder, and it may be necessary from time to time to give a stupid or misinformed beholder a black eye.» Miss Piggy
|
|
|
|
|
The hex thing is just a funny rule about "maybe out of range depending on how you look at them" integer literals, here's a simpler remedy:
int red = unchecked((int)0xFFFF0000); Still annoying because it needs the "unchecked" (as if I didn't know I was casting something out-of-range, that's the entire reason for casting!), also annoying (but for different reasons) are:
int red = 0xFFFF << 16;
int red = ~0x0000FFFF;
int red = -0x00010000; .. of course none of those generalize to arbitrary colors
Or perhaps more reasonably, but requiring a time machine: ToArgb and friends should have worked with uint . Problem solved, colours are more unsigned than signed anyway (I mean when do you ever think of white as -1?), inb4 "but CLS compliance".
BTW putting (un)checked around a function call doesn't do anything. It changes the codegen for primitive operations in its "scope", so it's not something that can be imposed on a callee.
|
|
|
|
|
Thanks, Harold,
Right now, the only way I can get back the "full" Color structure ... with fields 'NamedColor, etc., is to do a look-up in the KnownColor enumeration 'Values collection for matching integer values ... and that may result in more than one match : for each match the 'Key will be the full Color structure.
Will post code on request.
Seems like there should be an easier way to do that !
cheers, Bill
«Beauty is in the eye of the beholder, and it may be necessary from time to time to give a stupid or misinformed beholder a black eye.» Miss Piggy
|
|
|
|
|
Are you trying to serialize the Color ? That's the only time I can think of that you'd need to do this.
The obvious solution would be to combine IsKnownColor[^], ToKnownColor[^] and FromKnownColor[^]; and also IsNamedColor[^], Name[^] and FromName[^].
public struct ColorDetails : IEquatable<ColorDetails>
{
private ColorDetails(KnownColor knownColor, string name, int argb)
{
KnownColor = knownColor;
Name = name;
Argb = argb;
}
public KnownColor KnownColor { get; }
public string Name { get; }
public int Argb { get; }
public static ColorDetails FromColor(Color color)
{
if (color.IsKnownColor)
{
return new ColorDetails(color.ToKnownColor(), null, color.ToArgb());
}
if (color.IsNamedColor)
{
return new ColorDetails(0, color.Name, color.ToArgb());
}
return new ColorDetails(0, null, color.ToArgb());
}
public Color ToColor()
{
if (KnownColor != 0)
{
return Color.FromKnownColor(KnownColor);
}
if (Name != null)
{
return Color.FromName(Name);
}
return Color.FromArgb(Argb);
}
public override int GetHashCode()
{
return Argb;
}
public override bool Equals(object obj)
{
return obj is ColorDetails && Equals((ColorDetails)obj);
}
public bool Equals(ColorDetails other)
{
return Argb == other.Argb;
}
public static bool operator ==(ColorDetails left, ColorDetails right)
{
return left.Equals(right);
}
public static bool operator !=(ColorDetails left, ColorDetails right)
{
return !left.Equals(right);
}
}
ColorDetails cd = ColorDetails.FromColor(Color.Red);
Color clr = cd.ToColor();
bool ismatchEq1 = Color.Red.Equals(clr);
bool ismatchEq2 = Color.Red == clr;
bool isknown = clr.IsKnownColor;
bool isnamed = clr.IsNamedColor;
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi Richard,
Yes, I'm messing around with creating a Color extension for Yoshifumi Kawai's MessagePack open-source serializer: [^].
The speed and memory efficiency of MessagePack (which has optional built-in LZ4 compression) is, imho, remarkable.
I came up with something similar to your code, and implemented the required MessagePack 'Formatter and 'Resolver structures, but it had incredibly poor (slow) performance. So, I fell back on just making a simple class that saves a Color as either an integer, or a KnownColor name (string): this (excerpt) will give you an idea of what's going on:
[MessagePackObject]
public class MPColor
{
[Key(0)] public Int32 _colorAsInt32 = -1;
[Key(1)] public String _colorName = String.Empty;
public MPColor()
{
}
public MPColor(Color color)
{
MColor = color;
}
[IgnoreMember]
public Color MColor
{
set
{
if (value.IsKnownColor)
{
_colorAsInt32 = -1;
_colorName = value.Name;
}
else
{
_colorName = String.Empty;
_colorAsInt32 = value.ToArgb();
}
}
get
{
if (String.IsNullOrEmpty(_colorName))
{
if (_colorAsInt32 == -1)
{
return Color.Empty;
}
return Color.FromArgb(_colorAsInt32);
}
return Color.FromName(_colorName);
}
}
} This is quite fast and memory efficient. Since the KnownColor enumeration includes System Colors, that removes the need to store one aspect of state.
Tomorrow, I will study your code in depth, possibly try it out with the required 'Resolver and 'Formatter components in MessagePack.
As ever, really appreciate your quality responses !
cheers, Bill
«Beauty is in the eye of the beholder, and it may be necessary from time to time to give a stupid or misinformed beholder a black eye.» Miss Piggy
modified 3-Jul-17 9:56am.
|
|
|
|
|
i am printing a string through printer as the string length is more it is not getting printed properly so i have tried to split the string and the printing but it is showing error at run time
error:ex = {"Index and length must refer to a location within the string.\r\nParameter name: length"}
for (int i = 0; printstr != null; i++)
{
if (limit >printstrlength)
{
printstr = actualstring.Substring(startindex, printstrlength);
e.Graphics.DrawString(printstr, f1, Brushes.Black, new Point(x, y));
break;
}
else
{
printstr = actualstring.Substring(startindex, limit);
e.Graphics.DrawString(printstr, f1, Brushes.Black, new Point(x, y));
}
y += 20;
startindex = limit + 1;
limit += 40;
}
|
|
|
|
|
What it is saying is that when you try and do the Substring, the start index (or the start index plus the length of the bit you want to extract) must fit within the input string, and the numbers you have passed do not fit that criteria.
Use the debugger to look at the string and the values you pass to Substring and you should see which is wrong, and that should lead you to why it's wrong.
We can't do that for you - we don't have access to your strings!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
startindex = limit + 1;
limit += 40;
You are increasing limit by 40 each time round the loop. But you are also using this value to specify the length parameter in your call to actualstring.Substring(startindex, limit); , so sooner or later it will exceed the length of the remaining characters in the original string. You need to use a calculated value for the length, which starts at 40 but checks how many characters are still to be printed, each time round.
|
|
|
|
|