实例介绍
引用Android.UsbSerial 程序集;设备采用Type_C 转USB转换器与USB红外设备进行连接,根据设备类型在程序集中匹配合适驱动,通过报文的编码逻辑组织报文,以达到数据发送和接收的目的。
【实例截图】

【核心代码】
using Android.Icu.Text; using Android.Telephony.Euicc; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Hoho.Android.UsbSerial.Driver; using MauiUsbSerialForAndroid.Converter; using MauiUsbSerialForAndroid.Helper; using MauiUsbSerialForAndroid.Model; using Microsoft.Maui.Controls.Compatibility.Platform.Android; using System.Collections.ObjectModel; using System.Text; using System.Text.RegularExpressions;
namespace MauiUsbSerialForAndroid.ViewModel { [ObservableObject] public partial class SerialDataViewModel : IQueryAttributable { [ObservableProperty] bool isOpen = false; public UsbDeviceInfo DeviceInfo { get; set; } public string[] AllEncoding { get; } = new string[] { "HEX", "ASCII", "UTF-8", "GBK", "GB2312", "Unicode" }; public int[] AllBaudRate { get; } = new[] { 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 43000, 57600, 76800, 115200, 128000, 230400, 256000, 460800, 921600, 1382400 }; public int[] AllDataBits { get; } = new[] { 5, 6, 7, 8 }; public string[] AllParity { get; } = Enum.GetNames(typeof(Parity)); public string[] AllStopBits { get; } = Enum.GetNames(typeof(StopBits));
[ObservableProperty] string encodingSend = "HEX"; [ObservableProperty] string encodingReceive = "HEX"; [ObservableProperty] int intervalReceive = 50; [ObservableProperty] int intervalSend = 1000; [ObservableProperty] bool cycleToSend = false; [ObservableProperty] bool showTimeStamp = true; [ObservableProperty] bool autoScroll = true; [ObservableProperty] string sendData = ""; [ObservableProperty] SerialOption serialOption = new SerialOption(); [ObservableProperty] string softName = ""; // 终端地址; [ObservableProperty] string terminalAddr = "20785593"; //终端操作; [ObservableProperty] string terminalOperation = ""; //测量点操作; [ObservableProperty] string pointOperation = ""; //测量点编号; [ObservableProperty] string pointIndex = ""; //终端操作; [ObservableProperty] bool terminalChecked = true; //测量点操作; [ObservableProperty] bool pointChecked; //信息操作; [ObservableProperty] bool msgChecked; public ObservableCollection<SerialLog> Datas { get; } = new(); System.Timers.Timer timerSend; [ObservableProperty] string receivedText; public SerialDataViewModel() { SerialPortHelper.WhenDataReceived().Subscribe(data => { ReceivedText = SerialPortHelper.GetData(data, EncodingReceive); //Shell.Current.DisplayAlert("TooFast", ReceivedText, "ok"); if (receivedText.Length > 0) { AddLog(new SerialLog($"{TerminalAddr}: {TerminalOperation} 成功", false)); } else { AddLog(new SerialLog($"{TerminalAddr}: {TerminalOperation} 失败", false)); } //AddLog(new SerialLog($"终端地址:{convertedText}", false)); //AddLog(new SerialLog($"终端地址:{convertedText}", false)); }); timerSend = new System.Timers.Timer(intervalSend); timerSend.Elapsed = TimerSend_Elapsed; timerSend.Enabled = false;
SerialPortHelper.WhenUsbDeviceAttached((usbDevice) => { if (usbDevice.DeviceId == DeviceInfo.Device.DeviceId) { AddLog(new SerialLog("Usb device attached", false)); Open(); } });
SerialPortHelper.WhenUsbDeviceDetached((usbDevice) => { if (usbDevice.DeviceId == DeviceInfo.Device.DeviceId) { AddLog(new SerialLog("Usb device detached", false)); Close(); } }); } private void TimerSend_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Send(); } partial void OnIntervalReceiveChanged(int value) { SerialPortHelper.IntervalChange(value); } async partial void OnIntervalSendChanged(int value) { if (value < 5) { await Shell.Current.DisplayAlert("TooFast", "Set at least 5 milliseconds", "ok"); IntervalSend = 5; } timerSend.Interval = IntervalSend; } partial void OnCycleToSendChanged(bool value) { timerSend.Enabled = value; } Regex regHexRemove = new Regex("[^a-fA-F0-9 ]"); partial void OnSendDataChanged(string value) { if (EncodingSend == "HEX") { string temp = regHexRemove.Replace(value, ""); if (SendData != temp) { Shell.Current.DisplayAlert("Only hex", "Only HEX characters can be entered", "Ok"); SendData = temp; } } } public void ApplyQueryAttributes(IDictionary<string, object> query) { if (query.ContainsKey("Serial")) { DeviceInfo = (UsbDeviceInfo)query["Serial"]; Open(); } } [RelayCommand] public void Toggle() { if (IsOpen) { Close(); } else { Open(); } } [RelayCommand] public async void Open() { if (!IsOpen) { string r = await SerialPortHelper.RequestPermissionAsync(DeviceInfo); if (SerialPortHelper.CheckError(r, showDialog: false)) { r = SerialPortHelper.Open(DeviceInfo, SerialOption); if (SerialPortHelper.CheckError(r, showDialog: false)) { IsOpen = true; } else { AddLog(new SerialLog(r, false)); } } else { AddLog(new SerialLog(r, false)); } } } [RelayCommand] public void Close() { try { SerialPortHelper.Close(); CycleToSend = false; IsOpen = false; } catch (Exception) { } } [RelayCommand] public void Clear() { Datas.Clear(); } /// <summary> /// 发送信息,先判断是何种操作; /// </summary> [RelayCommand] public void Send() { if (SoftName.Length == 0) { Shell.Current.DisplayAlert("Choose right softname", "请选择合适的操作软件!", "Ok"); } else { if ("二层集抄".Equals(SoftName)) { EcjcConverter ecjc = new EcjcConverter(); if (terminalChecked is true) //如果是终端操作; { if (TerminalOperation.Equals("读终端地址")) { SendData = ecjc.ReadAddressMethod(TerminalAddr);
} else if ("写终端地址".Equals(TerminalOperation)) { SendData=ecjc.WriteAddressMethod(TerminalAddr);
} else if ("硬件初始化".Equals(TerminalOperation)) { SendData = ecjc.HardwareFormatingMethod(TerminalAddr);
} else if ("数据区初始化".Equals(TerminalOperation)) { SendData = ecjc.DataAreaFormatingMethod(TerminalAddr);
} } } // 不是二层集抄 else if ("GW376".Equals(SoftName)) { Gw376Converter gw376 = new Gw376Converter(); if (terminalChecked is true) //如果是终端操作; { if (TerminalOperation.Equals("读终端地址")) { SendData=gw376.ReadAddressMethod(TerminalAddr);
} else if ("写终端地址".Equals(TerminalOperation)) { SendData=gw376.WriteAddressMethod(this.terminalAddr);
} else if ("硬件初始化".Equals(TerminalOperation)) { SendData = gw376.HardwareFormatingMethod(TerminalAddr);
} else if ("数据区初始化".Equals(TerminalOperation)) { SendData=gw376.DataAreaFormatingMethod(TerminalAddr); } } } byte[] send = SerialPortHelper.GetBytes(SendData, EncodingSend); if (send.Length == 0) { return; } string s = SerialPortHelper.Write(send);
if (SerialPortHelper.CheckError(s)) { if (EncodingSend == "HEX") { //AddLog(new SerialLog(SendData.ToUpper(), true)); AddLog(new SerialLog($"{terminalOperation}:{TerminalAddr}", true)); } else { AddLog(new SerialLog(SendData, true)); } } else { AddLog(new SerialLog(s, true)); } } } [RelayCommand] public async void Back() { Close(); await Shell.Current.GoToAsync(".."); } void AddLog(SerialLog serialLog) { Datas.Add(serialLog);
//fix VirtualView cannot be null here Task.Delay(50); } [RelayCommand] void SerialOptionChange() { SerialPortHelper.SetOption(serialOption); } } } |
using CommunityToolkit.Mvvm.ComponentModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MauiUsbSerialForAndroid.Helper; using System.Collections.ObjectModel; using Hoho.Android.UsbSerial.Driver; using Android.Hardware.Usb; using CommunityToolkit.Mvvm.Input; using MauiUsbSerialForAndroid.Model; using MauiUsbSerialForAndroid.View; using Android.OS; using Android.Content; using Android.Util;
namespace MauiUsbSerialForAndroid.ViewModel { [ObservableObject] public partial class SerialPortViewModel : IQueryAttributable {
bool openIng = false; public ObservableCollection<UsbDeviceInfo> UsbDevices { get; } = new(); public SerialPortViewModel() { SerialPortHelper.WhenUsbDeviceAttached((usbDevice) => { GetUsbDevices(); });
SerialPortHelper.WhenUsbDeviceDetached((usbDevice) => { GetUsbDevices(); }); } public void ApplyQueryAttributes(IDictionary<string, object> query) { GetUsbDevices(); } [RelayCommand] public async Task GetUsbDevices() { UsbDevices.Clear(); var list = SerialPortHelper.GetUsbDevices(); foreach (var item in list) { UsbDevices.Add(item); //fix VirtualView cannot be null here await Task.Delay(50); } } [RelayCommand] async Task Open(UsbDeviceInfo usbDeviceInfo) { if (openIng) { return; } openIng = true; await Shell.Current.GoToAsync(nameof(SerialDataPage), new Dictionary<string, object> { { "Serial",usbDeviceInfo} }); openIng = false; }
} }
|
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论