Using one SerialPort instance without statics











up vote
0
down vote

favorite
1












To avoid making SerialPort static, my code is using inheritance to make sure the same SerialPort instance is being used.



In the application, only one COM port is to be used with the code. The first class i declare a new instance of serial port in the constructor. The second class, inherited from the first, doesn't need to create a new instance as it's base class has already been initialized once.



Please tell me if this is a good way to go about this. Also let me know what my bad habits are.



public class theSerialUsed
{
public SerialPort portSetup;
public theSerialUsed()
{
portSetup = new SerialPort(Global.COMPort, Int32.Parse(Global.baudRate), 0, 8);
portSetup.Encoding = System.Text.Encoding.UTF8;

}

//Check packet size of user data
public int checkdataSize(string r)
{
int result;
if (r.Length % 2 != 0)
{
result = (8 * r.Length / 2) + 4;
}
else { result = 8 * r.Length / 2; }
return result;
}

//Convert user data to hex val
public string ToHex(string input)
{
StringBuilder sb = new StringBuilder();
foreach (char c in input)
sb.AppendFormat("{0:X2}", (int)c);
return sb.ToString().Trim();
}

public string formatedData;
public string comment = "///This is a defaul (no) comment";

public string returnUserdataWithPrefix(string userData, string comment)
{
string FormattedCellCount = Global.SelectedCell.ToString();
if (comment != "")
{
this.comment = comment;
}


//Add the right abount of leading zeros to cells bwefore sending
if (Global.SelectedCell < 100 && Global.SelectedCell > 10)
{
FormattedCellCount = '0' + FormattedCellCount;
}
else if (Global.SelectedCell < 10) { FormattedCellCount = "00" + FormattedCellCount; }

//build final user datastring
formatedData = "css" + Global.SelectedWing.ToString() + FormattedCellCount + userData + this.comment + ';' + Global.SelectedUserID;

return formatedData;
}

}

public class convertAndSendData : theSerialUsed
{

//Send complete message to Serial Port
public void sendCollectedDataToPort(string userData, string comment)
{

//add prefix and surfix to userdata
userData = returnUserdataWithPrefix(userData, comment);
//Translate userdata into message into HEX>> Prefix PID and language type to msg
string result = "8204FF01" + ToHex(userData);

//Set Check sum from size of userdata
string packsize = checkdataSize(result).ToString();

try
{
portSetup.Open();

//send SDS-TL header
portSetup.Write("AT+CTSDS=12,0,0,0,0" + "rn");
Thread.Sleep(500);

////send receiver number and size of user data
portSetup.Write("AT+CMGS=" + Global.fepDestination + "," + packsize + "rn");
Thread.Sleep(500);

//Send user data with cntl-z command
portSetup.Write(result + "u001a");

//check response from radio
if (portSetup.ReadExisting().Contains("+CME ERROR:1") == false )
{
MessageBox.Show("Message Sent");
}
else
{
MessageBox.Show("Message Failed to send");
}
portSetup.Close();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": Is not connected to anything");
}
else if (ex is System.UnauthorizedAccessException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": is already in use");
}
else
{
throw;
}
}
}
}









share|improve this question




















  • 3




    IMO the inheriting doesn't buy you anything. If you create another instance of convertAndSendData a new SerialPort instance will be created. But maybe I don't get what you want.
    – Heslacher
    Nov 22 at 16:35










  • Create a single serial port and inject that into dependents
    – Nkosi
    Nov 22 at 22:25










  • Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
    – Nkosi
    Nov 22 at 22:27















up vote
0
down vote

favorite
1












To avoid making SerialPort static, my code is using inheritance to make sure the same SerialPort instance is being used.



In the application, only one COM port is to be used with the code. The first class i declare a new instance of serial port in the constructor. The second class, inherited from the first, doesn't need to create a new instance as it's base class has already been initialized once.



Please tell me if this is a good way to go about this. Also let me know what my bad habits are.



public class theSerialUsed
{
public SerialPort portSetup;
public theSerialUsed()
{
portSetup = new SerialPort(Global.COMPort, Int32.Parse(Global.baudRate), 0, 8);
portSetup.Encoding = System.Text.Encoding.UTF8;

}

//Check packet size of user data
public int checkdataSize(string r)
{
int result;
if (r.Length % 2 != 0)
{
result = (8 * r.Length / 2) + 4;
}
else { result = 8 * r.Length / 2; }
return result;
}

//Convert user data to hex val
public string ToHex(string input)
{
StringBuilder sb = new StringBuilder();
foreach (char c in input)
sb.AppendFormat("{0:X2}", (int)c);
return sb.ToString().Trim();
}

public string formatedData;
public string comment = "///This is a defaul (no) comment";

public string returnUserdataWithPrefix(string userData, string comment)
{
string FormattedCellCount = Global.SelectedCell.ToString();
if (comment != "")
{
this.comment = comment;
}


//Add the right abount of leading zeros to cells bwefore sending
if (Global.SelectedCell < 100 && Global.SelectedCell > 10)
{
FormattedCellCount = '0' + FormattedCellCount;
}
else if (Global.SelectedCell < 10) { FormattedCellCount = "00" + FormattedCellCount; }

//build final user datastring
formatedData = "css" + Global.SelectedWing.ToString() + FormattedCellCount + userData + this.comment + ';' + Global.SelectedUserID;

return formatedData;
}

}

public class convertAndSendData : theSerialUsed
{

//Send complete message to Serial Port
public void sendCollectedDataToPort(string userData, string comment)
{

//add prefix and surfix to userdata
userData = returnUserdataWithPrefix(userData, comment);
//Translate userdata into message into HEX>> Prefix PID and language type to msg
string result = "8204FF01" + ToHex(userData);

//Set Check sum from size of userdata
string packsize = checkdataSize(result).ToString();

try
{
portSetup.Open();

//send SDS-TL header
portSetup.Write("AT+CTSDS=12,0,0,0,0" + "rn");
Thread.Sleep(500);

////send receiver number and size of user data
portSetup.Write("AT+CMGS=" + Global.fepDestination + "," + packsize + "rn");
Thread.Sleep(500);

//Send user data with cntl-z command
portSetup.Write(result + "u001a");

//check response from radio
if (portSetup.ReadExisting().Contains("+CME ERROR:1") == false )
{
MessageBox.Show("Message Sent");
}
else
{
MessageBox.Show("Message Failed to send");
}
portSetup.Close();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": Is not connected to anything");
}
else if (ex is System.UnauthorizedAccessException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": is already in use");
}
else
{
throw;
}
}
}
}









share|improve this question




















  • 3




    IMO the inheriting doesn't buy you anything. If you create another instance of convertAndSendData a new SerialPort instance will be created. But maybe I don't get what you want.
    – Heslacher
    Nov 22 at 16:35










  • Create a single serial port and inject that into dependents
    – Nkosi
    Nov 22 at 22:25










  • Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
    – Nkosi
    Nov 22 at 22:27













up vote
0
down vote

favorite
1









up vote
0
down vote

favorite
1






1





To avoid making SerialPort static, my code is using inheritance to make sure the same SerialPort instance is being used.



In the application, only one COM port is to be used with the code. The first class i declare a new instance of serial port in the constructor. The second class, inherited from the first, doesn't need to create a new instance as it's base class has already been initialized once.



Please tell me if this is a good way to go about this. Also let me know what my bad habits are.



public class theSerialUsed
{
public SerialPort portSetup;
public theSerialUsed()
{
portSetup = new SerialPort(Global.COMPort, Int32.Parse(Global.baudRate), 0, 8);
portSetup.Encoding = System.Text.Encoding.UTF8;

}

//Check packet size of user data
public int checkdataSize(string r)
{
int result;
if (r.Length % 2 != 0)
{
result = (8 * r.Length / 2) + 4;
}
else { result = 8 * r.Length / 2; }
return result;
}

//Convert user data to hex val
public string ToHex(string input)
{
StringBuilder sb = new StringBuilder();
foreach (char c in input)
sb.AppendFormat("{0:X2}", (int)c);
return sb.ToString().Trim();
}

public string formatedData;
public string comment = "///This is a defaul (no) comment";

public string returnUserdataWithPrefix(string userData, string comment)
{
string FormattedCellCount = Global.SelectedCell.ToString();
if (comment != "")
{
this.comment = comment;
}


//Add the right abount of leading zeros to cells bwefore sending
if (Global.SelectedCell < 100 && Global.SelectedCell > 10)
{
FormattedCellCount = '0' + FormattedCellCount;
}
else if (Global.SelectedCell < 10) { FormattedCellCount = "00" + FormattedCellCount; }

//build final user datastring
formatedData = "css" + Global.SelectedWing.ToString() + FormattedCellCount + userData + this.comment + ';' + Global.SelectedUserID;

return formatedData;
}

}

public class convertAndSendData : theSerialUsed
{

//Send complete message to Serial Port
public void sendCollectedDataToPort(string userData, string comment)
{

//add prefix and surfix to userdata
userData = returnUserdataWithPrefix(userData, comment);
//Translate userdata into message into HEX>> Prefix PID and language type to msg
string result = "8204FF01" + ToHex(userData);

//Set Check sum from size of userdata
string packsize = checkdataSize(result).ToString();

try
{
portSetup.Open();

//send SDS-TL header
portSetup.Write("AT+CTSDS=12,0,0,0,0" + "rn");
Thread.Sleep(500);

////send receiver number and size of user data
portSetup.Write("AT+CMGS=" + Global.fepDestination + "," + packsize + "rn");
Thread.Sleep(500);

//Send user data with cntl-z command
portSetup.Write(result + "u001a");

//check response from radio
if (portSetup.ReadExisting().Contains("+CME ERROR:1") == false )
{
MessageBox.Show("Message Sent");
}
else
{
MessageBox.Show("Message Failed to send");
}
portSetup.Close();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": Is not connected to anything");
}
else if (ex is System.UnauthorizedAccessException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": is already in use");
}
else
{
throw;
}
}
}
}









share|improve this question















To avoid making SerialPort static, my code is using inheritance to make sure the same SerialPort instance is being used.



In the application, only one COM port is to be used with the code. The first class i declare a new instance of serial port in the constructor. The second class, inherited from the first, doesn't need to create a new instance as it's base class has already been initialized once.



Please tell me if this is a good way to go about this. Also let me know what my bad habits are.



public class theSerialUsed
{
public SerialPort portSetup;
public theSerialUsed()
{
portSetup = new SerialPort(Global.COMPort, Int32.Parse(Global.baudRate), 0, 8);
portSetup.Encoding = System.Text.Encoding.UTF8;

}

//Check packet size of user data
public int checkdataSize(string r)
{
int result;
if (r.Length % 2 != 0)
{
result = (8 * r.Length / 2) + 4;
}
else { result = 8 * r.Length / 2; }
return result;
}

//Convert user data to hex val
public string ToHex(string input)
{
StringBuilder sb = new StringBuilder();
foreach (char c in input)
sb.AppendFormat("{0:X2}", (int)c);
return sb.ToString().Trim();
}

public string formatedData;
public string comment = "///This is a defaul (no) comment";

public string returnUserdataWithPrefix(string userData, string comment)
{
string FormattedCellCount = Global.SelectedCell.ToString();
if (comment != "")
{
this.comment = comment;
}


//Add the right abount of leading zeros to cells bwefore sending
if (Global.SelectedCell < 100 && Global.SelectedCell > 10)
{
FormattedCellCount = '0' + FormattedCellCount;
}
else if (Global.SelectedCell < 10) { FormattedCellCount = "00" + FormattedCellCount; }

//build final user datastring
formatedData = "css" + Global.SelectedWing.ToString() + FormattedCellCount + userData + this.comment + ';' + Global.SelectedUserID;

return formatedData;
}

}

public class convertAndSendData : theSerialUsed
{

//Send complete message to Serial Port
public void sendCollectedDataToPort(string userData, string comment)
{

//add prefix and surfix to userdata
userData = returnUserdataWithPrefix(userData, comment);
//Translate userdata into message into HEX>> Prefix PID and language type to msg
string result = "8204FF01" + ToHex(userData);

//Set Check sum from size of userdata
string packsize = checkdataSize(result).ToString();

try
{
portSetup.Open();

//send SDS-TL header
portSetup.Write("AT+CTSDS=12,0,0,0,0" + "rn");
Thread.Sleep(500);

////send receiver number and size of user data
portSetup.Write("AT+CMGS=" + Global.fepDestination + "," + packsize + "rn");
Thread.Sleep(500);

//Send user data with cntl-z command
portSetup.Write(result + "u001a");

//check response from radio
if (portSetup.ReadExisting().Contains("+CME ERROR:1") == false )
{
MessageBox.Show("Message Sent");
}
else
{
MessageBox.Show("Message Failed to send");
}
portSetup.Close();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": Is not connected to anything");
}
else if (ex is System.UnauthorizedAccessException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": is already in use");
}
else
{
throw;
}
}
}
}






c# serial-port






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 20:43









200_success

127k15148412




127k15148412










asked Nov 22 at 16:24









Mrparkin

11




11








  • 3




    IMO the inheriting doesn't buy you anything. If you create another instance of convertAndSendData a new SerialPort instance will be created. But maybe I don't get what you want.
    – Heslacher
    Nov 22 at 16:35










  • Create a single serial port and inject that into dependents
    – Nkosi
    Nov 22 at 22:25










  • Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
    – Nkosi
    Nov 22 at 22:27














  • 3




    IMO the inheriting doesn't buy you anything. If you create another instance of convertAndSendData a new SerialPort instance will be created. But maybe I don't get what you want.
    – Heslacher
    Nov 22 at 16:35










  • Create a single serial port and inject that into dependents
    – Nkosi
    Nov 22 at 22:25










  • Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
    – Nkosi
    Nov 22 at 22:27








3




3




IMO the inheriting doesn't buy you anything. If you create another instance of convertAndSendData a new SerialPort instance will be created. But maybe I don't get what you want.
– Heslacher
Nov 22 at 16:35




IMO the inheriting doesn't buy you anything. If you create another instance of convertAndSendData a new SerialPort instance will be created. But maybe I don't get what you want.
– Heslacher
Nov 22 at 16:35












Create a single serial port and inject that into dependents
– Nkosi
Nov 22 at 22:25




Create a single serial port and inject that into dependents
– Nkosi
Nov 22 at 22:25












Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
– Nkosi
Nov 22 at 22:27




Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
– Nkosi
Nov 22 at 22:27















active

oldest

votes











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208238%2fusing-one-serialport-instance-without-statics%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208238%2fusing-one-serialport-instance-without-statics%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Сан-Квентин

8-я гвардейская общевойсковая армия

Алькесар