Skip to content

Instantly share code, notes, and snippets.

@fleaplus
Created January 15, 2021 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fleaplus/33810c36236438d074abaaa90a586991 to your computer and use it in GitHub Desktop.
Save fleaplus/33810c36236438d074abaaa90a586991 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using Xamarin.Forms;
namespace My_Climate_App
{
enum ResponseStatus
{
SUCCESS,
FAILURE
}
class SerialOperation
{
protected ISerial _serialDevice;
protected string _response = "";
public SerialOperation() { }
public (ResponseStatus, string) Run()
{
_serialDevice = DependencyService.Get<ISerial>();
if (_serialDevice != null)
{
try
{
SendCommand();
_response = _serialDevice.ReadLine();
}
catch (InvalidOperationException e)
{
System.Diagnostics.Debug.WriteLine($"USBSerialService InvalidOperationException occured: {e.Message}");
}
catch (TimeoutException e)
{
System.Diagnostics.Debug.WriteLine($"USBSerialService TimeoutException occured: {e.Message}");
}
if (Valid(_response))
{
return (ResponseStatus.SUCCESS, Parse(_response));
}
else
{
return (ResponseStatus.FAILURE, "Invalid Response, Unknown");
}
}
else
{
throw new Exception("platform not implemented");
}
}
virtual protected void SendCommand()
{
throw new Exception();
}
virtual protected bool Valid(string response)
{
throw new Exception();
}
virtual protected string Parse(string response)
{
return "";
}
}
class GetFirmwareVersionOperation : SerialOperation
{
const string GET_FIRMWARE_REVISION = "GR";
const string RESPONSE_FIRMWARE_REVISION = "RR,";
override protected void SendCommand()
{
_serialDevice.WriteLine(GET_FIRMWARE_REVISION);
}
override protected bool Valid(string response)
{
return response.Contains(RESPONSE_FIRMWARE_REVISION);
}
override protected string Parse(string serialResponse)
{
return serialResponse.Replace(RESPONSE_FIRMWARE_REVISION, "");
}
}
class SetHelpLightOperation : SerialOperation
{
private string _value;
public SetHelpLightOperation(string value = "") : base()
{
_value = value;
}
override protected void SendCommand()
{
_serialDevice.WriteLine($"SL4,{_value}");
}
override protected bool Valid(string response)
{
return response.Contains("AL4,1");
}
}
class UseIt
{
public UseIt()
{
(ResponseStatus status, string message) response;
response = new GetFirmwareVersionOperation().Run();
if (response.status != ResponseStatus.SUCCESS)
{
// toast - firmware revision unavailable
}
else
{
return response.message;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment