ASP NET, NET Framework, MONO, SQL, Visual Studio | Professional Programs | Программист Еремин В.В.
(SOFT) SOFT (2009 год)

ComDetector - утилита поиска COM-оборудования

Я очень люблю ковырятся со всевозможными компьютерными устройствами, например Эра цифрового TV, Сборка 1U сервера, Электронный замок, Сторожевой таймер EXPPAY, Игрушки для взрослых мальчиков. И однажды мне понадобилась утилита, которая бы могла понять - шнур от какого именно COM-порта (из восьми имеющихся на кампутере портов) я держу в руках.

Потом я столкнулся с терминальным модемом Siemens MC35i, который откликался только на скорости 115200 бод. Потом мне понадобилось посмотреть статус принтера на удаленном от меня терминале Custom VKP80. Таким образом и получилась за несколько приемов утилита, которая перед вами.

Я сделал эту утилиту на MONO по такой же точно технологии, как GoogleTranslate - англо-русский онлайн переводчик - так что работать она может не только в виндузне, но и на загрузочных компактах и флешках LINUX - Загрузочные компакты и флешки (bootable LiveCD and bootable USB).


В утилите уже заложено много возможностей - но я распространяю свой код на условиях GNU Lesser General Public License - поэтому вы имеете право скопировать мой код, исправить его и дополнить любым своим функионалом.

Моя утилита - консольное приложение (впрочем вам ничто не мешает либо докрутить сюда GUI либо вызвать ее из командной строки и обработать ее листинг своим софтом). Она перебирает все последовательные COM-интерфейсы в поисках оборудования, которое ей указано в параметре SearchType. На рисунках вы видите, как выглядят параметры моей утилиты и оборудование, которое я ею обычно тестирую.

Если ваше автономное коммуникационное оборудование требует +12, +5, -12 вольт - просто закорачивайте зеленый контакт и черный на разъеме ATX блока питания, чтобы включить свое автономное оборудование на стандартном кампутерном ATX блоке питания (это вы можете видеть на рисунке сверху).

Учтите, что COM-обрудование горит просто отлично - это не панты какие-нибудь, а реальность. Даже сейчас, когда я работаю один, у меня половина выгоревших портов на кампутерах - стоит потерять бдительность и тыкнуть что-нибудь на горячее - COM-порт сразу же сгорает. А когда я работал админом института с 300-ми кампами - у меня там вообще остался на всю серверную один рабочий порт - потому что там был проходной двор среди моих помошников-младших админов. Это не относится к NULL-modem - его можно включать на горячую свободно.

В режиме нуль-модема SearchType=Echo - задача проги - зафиксировать факт эха на каком-нибудь из COM-интерфейсов. Тогда вы понимаете на каком именно кабеле сейчас находится null-modem. Как видите, на COM2 интерфейсе эха нет, а на COM1 - есть эхо, причем посколько программа работает универсально, без контроля скорости работы оборудования, то два последних байта не дочитались (интерфейс призадумался перед тем как из выдать) - поэтому получается сообщение об ошибке эха нуль-модема.

Чуть правее вы видите режим подбора четности и старт-стопного бита последовательного интерфейса - и чудеса в данных отклика нуль-модема, которые происходят при неверных установках databits, parity и stopbits у последовательного порта.

При работе на неправильных скоростях (speed=search)COM-оборудование ведет себя просто чудестно. В часности принтер VKP80 не только заминает бумагу, но и печатает жуткую абракадабру. Ее вы можете видеть на рисунке - ниже слева. А чуть правее скрин - протокол работы моей проги в режиме SearchType=vkp80- как видите, состояния сенсоров принтера и его статус на низких скоростях там вовсе не читается. А на правом скрине вы видите принтер, который вне зависимости от настроек порта откликается только на скорости 19200. Поэтому, чтобы не мучать принтер, рекомендуется все-таки включить принтер с нажатой кнопкой LF и он напечатает свои настроки (это правый чек на левом рисунке).

Однако с терминальным модемом так не получится - узнать на какую скорость он настроен. Модем нормально откликается только на определенной скорости (чаще всего 115200), но заранее она неизвестна, а чек со своими настройками он выдать не может. Правее вы видите как ведет себя модем на разных скоростях - в режиме работы проги SearchType=modem. Как видите, он вообще начал откликаться начиная со скоростей 19600 бод.

Это ровно тот же самый отклик, которым мы видим в программе putty или HyperTerminal. Вы можете передать в параметре ModemCommand другую команду (вместо AT&V) - и таким образом работать с любым своим коммуникационным оборудованием.

Собственно код моей проги состоит из трех фрагментов - одного модуля и трех статических классов. В стартовом модуле я обработал все параметры командной строки и организовал нужные рабочие циклы:


   1:  Module Start
   2:   
   3:      Sub Main()
   4:          Try
   5:              Dim PRM() As String = Environment.GetCommandLineArgs
   6:              For j As Integer = 1 To PRM.Length - 1
   7:                  Dim OneParm As String = PRM(j)
   8:                  Dim X() As String = OneParm.ToLower.Split("=")
   9:                  If X.Length = 0 Then GoTo usage
  10:                  Select Case X(0)
  11:                      Case "searchtype"
  12:                          Select Case X(1)
  13:                              Case "echo" : UserParm.SearchType = UserParm.ExecType.Echo
  14:                              Case "modem" : UserParm.SearchType = UserParm.ExecType.Modem
  15:                              Case "vkp80" : UserParm.SearchType = UserParm.ExecType.VKP80
  16:                              Case Else
  17:                                  Console.WriteLine("SearchType=?")
  18:                                  GoTo usage
  19:                          End Select
  20:                      Case "comport"
  21:                          Select Case X(1)
  22:                              Case "search" : UserParm.PortName = UserParm.ExecPortName.Search
  23:                              Case "com1" : UserParm.PortName = UserParm.ExecPortName.COM1
  24:                              Case "com2" : UserParm.PortName = UserParm.ExecPortName.COM2
  25:                              Case "com3" : UserParm.PortName = UserParm.ExecPortName.COM3
  26:                              Case "com4" : UserParm.PortName = UserParm.ExecPortName.COM4
  27:                              Case "com5" : UserParm.PortName = UserParm.ExecPortName.COM5
  28:                              Case "com6" : UserParm.PortName = UserParm.ExecPortName.COM6
  29:                              Case "com7" : UserParm.PortName = UserParm.ExecPortName.COM7
  30:                              Case "com8" : UserParm.PortName = UserParm.ExecPortName.COM8
  31:                              Case Else
  32:                                  Console.WriteLine("ComPort=?")
  33:                                  GoTo usage
  34:                          End Select
  35:                      Case "speed"
  36:                          Select Case X(1)
  37:                              Case "current" : UserParm.Speed = UserParm.ExecSpeed.Current
  38:                              Case "search" : UserParm.Speed = UserParm.ExecSpeed.Search
  39:                              Case "110" : UserParm.Speed = UserParm.ExecSpeed.s110
  40:                              Case "300" : UserParm.Speed = UserParm.ExecSpeed.s300
  41:                              Case "1200" : UserParm.Speed = UserParm.ExecSpeed.s1200
  42:                              Case "2400" : UserParm.Speed = UserParm.ExecSpeed.s2400
  43:                              Case "4800" : UserParm.Speed = UserParm.ExecSpeed.s4800
  44:                              Case "9600" : UserParm.Speed = UserParm.ExecSpeed.s9600
  45:                              Case "19200" : UserParm.Speed = UserParm.ExecSpeed.s19200
  46:                              Case "38400" : UserParm.Speed = UserParm.ExecSpeed.s38400
  47:                              Case "57600" : UserParm.Speed = UserParm.ExecSpeed.s57600
  48:                              Case "115200" : UserParm.Speed = UserParm.ExecSpeed.s115200
  49:                              Case "230400" : UserParm.Speed = UserParm.ExecSpeed.s230400
  50:                              Case Else
  51:                                  Console.WriteLine("Speed=?")
  52:                                  GoTo usage
  53:                          End Select
  54:                      Case "parity"
  55:                          Select Case X(1)
  56:                              Case "current" : UserParm.Parity = UserParm.ExecParity.Current
  57:                              Case "search" : UserParm.Parity = UserParm.ExecParity.Search
  58:                              Case "even" : UserParm.Parity = UserParm.ExecParity.Even
  59:                              Case "mark" : UserParm.Parity = UserParm.ExecParity.Mark
  60:                              Case "none" : UserParm.Parity = UserParm.ExecParity.None
  61:                              Case "odd" : UserParm.Parity = UserParm.ExecParity.Odd
  62:                              Case "space" : UserParm.Parity = UserParm.ExecParity.Space
  63:                              Case Else
  64:                                  Console.WriteLine("Parity=?")
  65:                                  GoTo usage
  66:                          End Select
  67:                      Case "databits"
  68:                          Select Case X(1)
  69:                              Case "current" : UserParm.Databits = UserParm.ExecDatabits.Current
  70:                              Case "search" : UserParm.Databits = UserParm.ExecDatabits.Search
  71:                              Case "5" : UserParm.Databits = UserParm.ExecDatabits.d5
  72:                              Case "6" : UserParm.Databits = UserParm.ExecDatabits.d6
  73:                              Case "7" : UserParm.Databits = UserParm.ExecDatabits.d7
  74:                              Case "8" : UserParm.Databits = UserParm.ExecDatabits.d8
  75:                              Case Else
  76:                                  Console.WriteLine("Parity=?")
  77:                                  GoTo usage
  78:                          End Select
  79:                      Case "stopbits"
  80:                          Select Case X(1)
  81:                              Case "current" : UserParm.Stopbits = UserParm.ExecStopBits.Current
  82:                              Case "search" : UserParm.Stopbits = UserParm.ExecStopBits.Search
  83:                              Case "none" : UserParm.Stopbits = UserParm.ExecStopBits.None
  84:                              Case "one" : UserParm.Stopbits = UserParm.ExecStopBits.One
  85:                              Case "onepointfive" : UserParm.Stopbits = UserParm.ExecStopBits.OnePointFive
  86:                              Case "two" : UserParm.Stopbits = UserParm.ExecStopBits.Two
  87:                              Case Else
  88:                                  Console.WriteLine("Parity=?")
  89:                                  GoTo usage
  90:                          End Select
  91:                      Case "modemcommand"
  92:                          UserParm.ModemCommand = X(1)
  93:                      Case "tuningsleep"
  94:                          Select Case X(1)
  95:                              Case "manual" : UserParm.TuningSleep = -1
  96:                              Case Else
  97:                                  Try
  98:                                      UserParm.TuningSleep = CInt(X(1))
  99:                                  Catch ex As Exception
 100:                                      Console.WriteLine("TuningSleep=?")
 101:                                      GoTo usage
 102:                                  End Try
 103:                          End Select
 104:                      Case "list"
 105:                          Select Case X(1)
 106:                              Case "short" : UserParm.Listing = UserParm.ExecListingType.Short
 107:                              Case "full" : UserParm.Listing = UserParm.ExecListingType.Full
 108:                          End Select
 109:                      Case "timeout"
 110:                          Try
 111:                              UserParm.Timeout = CInt(X(1))
 112:                          Catch ex As Exception
 113:                              Console.WriteLine("Timeout=?")
 114:                              GoTo usage
 115:                          End Try
 116:                      Case Else
 117:                          Console.WriteLine("What is " & X(0) & "?")
 118:                          GoTo usage
 119:                  End Select
 120:              Next
 121:              'all input parameters checked and correct
 122:   
 123:   
 124:              If UserParm.PortName = UserParm.ExecPortName.Search Then
 125:                  For Each PortName As String In My.Computer.Ports.SerialPortNames
 126:                      OneSerialPort(PortName)
 127:                  Next
 128:              Else
 129:                  OneSerialPort(UserParm.PortName.ToString)
 130:              End If
 131:              Console.ReadLine()
 132:              Exit Sub
 133:  usage:
 134:              Console.WriteLine("Usage: ComDetector [SearchType=Echo -or- Modem -or- VKP80] [ComPort=PortName -or- search] [Speed=value -or- search -or- current] [Parity=value -or- search -or- current] [Databits=value -or- search -or- current] [StopBits=value -or- search -or- current] [Timeout=1000] [TuningSleep=100 or Manual] [List=Full -or- Short] [ModemCommand=AT&V]")
 135:              Console.WriteLine()
 136:              Console.WriteLine("Example1: ComDetector ComPort=search SearchType=Echo Speed=115200 Sleep=100 -- search echo (null-modem) on each COM-interface with sleep 0,1 second on speen 115200 bod and current parity, databits, stopbits")
 137:              Console.WriteLine()
 138:              Console.WriteLine("Example2: ComDetector SearchType=VKP80 ComPort=COM1 Databits=search StopBits=search Parity=search StopBits=Node -- search VKP80 printer on COM-interface on any speed, parity, databits, stopbits=One")
 139:              Console.WriteLine()
 140:              Console.WriteLine("Example3: ComDetector SearchType=Modem speed=current Timeout=1000 Enum=manual -- search modem (AT&V) on each COM-interface on any parity, databits, stopbits with ReadTimeout one second and current serial port speed with manual change each port tuning.")
 141:              Console.WriteLine()
 142:              Console.WriteLine("All parameter name may be in upper or lower case, all parameters (except SearchType) may be omitted, all parameters may be in any order, example ComDetector  paRity=None searchType=vkp80 ComPort=com7. If parameter omitted use current value.")
 143:              Console.WriteLine()
 144:              Console.WriteLine("Speed=110,300,1200,2400,4800,9600,19200,38400,57600,115200,230400; Parity=None,Odd,Even,Mark,Space; Databits=5,6,7,8; StopBits=None,One,OnePointFive,Two")
 145:              Console.WriteLine("Default SearchType=Echo, ComPort=search, Speed=Current, Parity=None, Databits=8, StopBits=One, TuningSleep=100, List=Full, ModemCommand=AT&V")
 146:   
 147:              Console.WriteLine()
 148:              Console.WriteLine("In Linux execute IL byte code as: mono ComDetector.exe SearchType=Echo or create binary file on you processor architecture from IL-code as : mkbundle -o comdetector ComDetector.exe --deps")
 149:              Console.WriteLine()
 150:              Console.ReadLine()
 151:          Catch ex As Exception
 152:              Console.WriteLine("Error occured: " & vbCrLf & ex.Message)
 153:          End Try
 154:   
 155:      End Sub
 156:   
 157:      Sub OneSerialPort(ByVal ComPortName As String)
 158:          Console.WriteLine()
 159:          Console.WriteLine(ComPortName & vbCrLf)
 160:          Try
 161:              Port.ComPort.Close()
 162:          Catch ex As Exception
 163:              '
 164:          End Try
 165:          Try
 166:              Select Case UserParm.Speed
 167:                  Case UserParm.ExecSpeed.Search
 168:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s110)
 169:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s300)
 170:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s1200)
 171:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s2400)
 172:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s4800)
 173:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s9600)
 174:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s19200)
 175:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s38400)
 176:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s57600)
 177:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s115200)
 178:                      ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s230400)
 179:   
 180:                  Case UserParm.ExecSpeed.Current
 181:                      Dim Speed As Port.Speed
 182:                      Try
 183:                          Dim X As IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(ComPortName)
 184:                          Speed = X.BaudRate
 185:                          X.Close()
 186:                      Catch ex As Exception
 187:                          Console.WriteLine("Error reading current Speed on " & ComPortName)
 188:                          Exit Sub
 189:                      End Try
 190:                      Select Case Speed
 191:                          Case 110 : Speed = UserParm.ExecSpeed.s110
 192:                          Case 300 : Speed = UserParm.ExecSpeed.s300
 193:                          Case 1200 : Speed = UserParm.ExecSpeed.s1200
 194:                          Case 2400 : Speed = UserParm.ExecSpeed.s2400
 195:                          Case 4800 : Speed = UserParm.ExecSpeed.s4800
 196:                          Case 9600 : Speed = UserParm.ExecSpeed.s9600
 197:                          Case 19200 : Speed = UserParm.ExecSpeed.s19200
 198:                          Case 38400 : Speed = UserParm.ExecSpeed.s38400
 199:                          Case 57600 : Speed = UserParm.ExecSpeed.s57600
 200:                          Case 115200 : Speed = UserParm.ExecSpeed.s115200
 201:                          Case 230400 : Speed = UserParm.ExecSpeed.s230400
 202:                      End Select
 203:                      ProcessOneSpeed(ComPortName, Speed)
 204:   
 205:                  Case UserParm.ExecSpeed.s110 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s110)
 206:                  Case UserParm.ExecSpeed.s300 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s300)
 207:                  Case UserParm.ExecSpeed.s1200 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s1200)
 208:                  Case UserParm.ExecSpeed.s2400 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s2400)
 209:                  Case UserParm.ExecSpeed.s4800 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s4800)
 210:                  Case UserParm.ExecSpeed.s9600 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s9600)
 211:                  Case UserParm.ExecSpeed.s19200 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s19200)
 212:                  Case UserParm.ExecSpeed.s38400 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s38400)
 213:                  Case UserParm.ExecSpeed.s57600 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s115200)
 214:                  Case UserParm.ExecSpeed.s115200 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s115200)
 215:                  Case UserParm.ExecSpeed.s230400 : ProcessOneSpeed(ComPortName, UserParm.ExecSpeed.s230400)
 216:              End Select
 217:   
 218:          Catch ex As Exception
 219:              Console.WriteLine(ComPortName & " error occured: " & vbCrLf & ex.Message)
 220:              Try
 221:                  Port.Close()
 222:              Catch x As Exception
 223:                  '
 224:              End Try
 225:          End Try
 226:      End Sub
 227:   
 228:      Sub ProcessOneSpeed(ByVal ComPortName As String, ByVal Speed As Port.Speed)
 229:          Try
 230:              Select Case UserParm.Databits
 231:                  Case UserParm.ExecDatabits.Current
 232:                      Dim Databits As Port.Databits
 233:                      Try
 234:                          Dim X As IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(ComPortName)
 235:                          Databits = X.DataBits
 236:                          X.Close()
 237:                      Catch ex As Exception
 238:                          Console.WriteLine("Error reading current DataBits on " & ComPortName)
 239:                          Exit Sub
 240:                      End Try
 241:                      Select Case Databits
 242:                          Case 8 : Databits = Port.Databits.d8
 243:                          Case 7 : Databits = Port.Databits.d7
 244:                          Case 6 : Databits = Port.Databits.d6
 245:                          Case 5 : Databits = Port.Databits.d5
 246:                      End Select
 247:                      ProcessOneDatabits(ComPortName, Speed, Databits)
 248:   
 249:                  Case UserParm.ExecDatabits.Search
 250:                      ProcessOneDatabits(ComPortName, Speed, Port.Databits.d8)
 251:                      ProcessOneDatabits(ComPortName, Speed, Port.Databits.d7)
 252:                      ProcessOneDatabits(ComPortName, Speed, Port.Databits.d6)
 253:                      ProcessOneDatabits(ComPortName, Speed, Port.Databits.d5)
 254:   
 255:                  Case UserParm.ExecDatabits.d8 : ProcessOneDatabits(ComPortName, Speed, Port.Databits.d8)
 256:                  Case UserParm.ExecDatabits.d7 : ProcessOneDatabits(ComPortName, Speed, Port.Databits.d7)
 257:                  Case UserParm.ExecDatabits.d6 : ProcessOneDatabits(ComPortName, Speed, Port.Databits.d6)
 258:                  Case UserParm.ExecDatabits.d5 : ProcessOneDatabits(ComPortName, Speed, Port.Databits.d5)
 259:              End Select
 260:          Catch ex As Exception
 261:              Console.WriteLine(ComPortName & " error occured: " & " Speed = " & Speed.ToString & vbCrLf & ex.Message)
 262:              Try
 263:                  Port.Close()
 264:              Catch x As Exception
 265:                  '
 266:              End Try
 267:          End Try
 268:   
 269:      End Sub
 270:   
 271:      Sub ProcessOneDatabits(ByVal ComPortName As String, ByVal Speed As Port.Speed, ByVal Databits As Port.Databits)
 272:          Try
 273:              Select Case UserParm.Parity
 274:                  Case UserParm.ExecDatabits.Current
 275:                      Dim Parity As IO.Ports.Parity
 276:                      Try
 277:                          Dim X As IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(ComPortName)
 278:                          Parity = X.Parity
 279:                          X.Close()
 280:                      Catch ex As Exception
 281:                          Console.WriteLine("Error reading current Parity on " & ComPortName)
 282:                          Exit Sub
 283:                      End Try
 284:                      Select Case Parity
 285:                          Case IO.Ports.Parity.None : Parity = IO.Ports.Parity.None
 286:                          Case IO.Ports.Parity.Mark : Parity = IO.Ports.Parity.Mark
 287:                          Case IO.Ports.Parity.Even : Parity = IO.Ports.Parity.Even
 288:                          Case IO.Ports.Parity.Odd : Parity = IO.Ports.Parity.Odd
 289:                          Case IO.Ports.Parity.Space : Parity = IO.Ports.Parity.Space
 290:                      End Select
 291:                      ProcessOneParity(ComPortName, Speed, Databits, Parity)
 292:   
 293:                  Case UserParm.ExecParity.Search
 294:                      ProcessOneParity(ComPortName, Speed, Databits, IO.Ports.Parity.None)
 295:                      ProcessOneParity(ComPortName, Speed, Databits, IO.Ports.Parity.Mark)
 296:                      ProcessOneParity(ComPortName, Speed, Databits, IO.Ports.Parity.Even)
 297:                      ProcessOneParity(ComPortName, Speed, Databits, IO.Ports.Parity.Odd)
 298:                      ProcessOneParity(ComPortName, Speed, Databits, IO.Ports.Parity.Space)
 299:                  Case UserParm.ExecParity.None : ProcessOneParity(ComPortName, Speed, Databits, IO.Ports.Parity.None)
 300:                  Case UserParm.ExecParity.Odd : ProcessOneParity(ComPortName, Speed, Databits, IO.Ports.Parity.Odd)
 301:                  Case UserParm.ExecParity.Even : ProcessOneParity(ComPortName, Speed, Databits, IO.Ports.Parity.Even)
 302:                  Case UserParm.ExecParity.Mark : ProcessOneParity(ComPortName, Speed, Databits, IO.Ports.Parity.Mark)
 303:                  Case UserParm.ExecParity.Space : ProcessOneParity(ComPortName, Speed, Databits, IO.Ports.Parity.Space)
 304:              End Select
 305:          Catch ex As Exception
 306:              Console.WriteLine(ComPortName & " error occured: " & " Speed = " & Speed.ToString & ", Databits=" & Databits.ToString & vbCrLf & ex.Message)
 307:              Try
 308:                  Port.Close()
 309:              Catch x As Exception
 310:                  '
 311:              End Try
 312:          End Try
 313:   
 314:      End Sub
 315:   
 316:      Sub ProcessOneParity(ByVal ComPortName As String, ByVal Speed As Port.Speed, ByVal Databits As Port.Databits, ByVal Parity As IO.Ports.Parity)
 317:          Try
 318:              Select Case UserParm.Stopbits
 319:                  Case UserParm.ExecStopBits.Current
 320:                      Dim Stopbits As IO.Ports.StopBits
 321:                      Try
 322:                          Dim X As IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(ComPortName)
 323:                          Stopbits = X.StopBits
 324:                          X.Close()
 325:                      Catch ex As Exception
 326:                          Console.WriteLine("Error reading current Stopbits on " & ComPortName)
 327:                          Exit Sub
 328:                      End Try
 329:                      Select Case Stopbits
 330:                          Case IO.Ports.StopBits.None : Stopbits = IO.Ports.StopBits.None
 331:                          Case IO.Ports.StopBits.One : Stopbits = IO.Ports.StopBits.One
 332:                          Case IO.Ports.StopBits.OnePointFive : Stopbits = IO.Ports.StopBits.OnePointFive
 333:                          Case IO.Ports.StopBits.Two : Stopbits = IO.Ports.StopBits.Two
 334:                      End Select
 335:                      ProcessOneStopbits(ComPortName, Speed, Databits, Parity, Stopbits)
 336:                  Case UserParm.ExecStopBits.Search
 337:                      ProcessOneStopbits(ComPortName, Speed, Databits, Parity, IO.Ports.StopBits.None)
 338:                      ProcessOneStopbits(ComPortName, Speed, Databits, Parity, IO.Ports.StopBits.One)
 339:                      ProcessOneStopbits(ComPortName, Speed, Databits, Parity, IO.Ports.StopBits.OnePointFive)
 340:                      ProcessOneStopbits(ComPortName, Speed, Databits, Parity, IO.Ports.StopBits.Two)
 341:                  Case UserParm.ExecStopBits.None : ProcessOneStopbits(ComPortName, Speed, Databits, Parity, IO.Ports.StopBits.None)
 342:                  Case UserParm.ExecStopBits.One : ProcessOneStopbits(ComPortName, Speed, Databits, Parity, IO.Ports.StopBits.One)
 343:                  Case UserParm.ExecStopBits.OnePointFive : ProcessOneStopbits(ComPortName, Speed, Databits, Parity, IO.Ports.StopBits.OnePointFive)
 344:                  Case UserParm.ExecStopBits.Two : ProcessOneStopbits(ComPortName, Speed, Databits, Parity, IO.Ports.StopBits.Two)
 345:              End Select
 346:          Catch ex As Exception
 347:              Console.WriteLine(ComPortName & " error occured: " & " Speed = " & Speed.ToString & ", Databits=" & Databits.ToString & ", Parity=" & Parity.ToString & vbCrLf & ex.Message)
 348:              Try
 349:                  Port.Close()
 350:              Catch x As Exception
 351:                  '
 352:              End Try
 353:          End Try
 354:      End Sub
 355:   
 356:      Sub ProcessOneStopbits(ByVal ComPortName As String, ByVal Speed As Port.Speed, ByVal Databits As Port.Databits, ByVal Parity As IO.Ports.Parity, ByVal Stopbits As IO.Ports.StopBits)
 357:          Console.WriteLine(ComPortName & " : " & " Speed = " & Speed.ToString & ", Databits=" & Databits.ToString & ", Parity=" & Parity.ToString & ", Stopbits=" & Stopbits.ToString)
 358:   
 359:          Try
 360:              If UserParm.TuningSleep = -1 Then
 361:                  Console.WriteLine("Press enter to write data ...")
 362:                  Console.ReadLine()
 363:              Else
 364:                  System.Threading.Thread.Sleep(UserParm.TuningSleep)
 365:              End If
 366:              Port.Open(ComPortName, Speed, Parity, Databits, Stopbits, UserParm.Timeout)
 367:              Select Case UserParm.SearchType
 368:                  Case UserParm.ExecType.Echo : ProcessEcho()
 369:                  Case UserParm.ExecType.Modem : ProcessModem()
 370:                  Case UserParm.ExecType.VKP80 : ProcessVKP80()
 371:              End Select
 372:              If UserParm.Listing = UserParm.ExecListingType.Full Then
 373:                  Console.WriteLine(Port.GetPortStatus())
 374:              End If
 375:              Port.Close()
 376:          Catch ex As Exception
 377:              Console.WriteLine(ComPortName & " error occured: " & " Speed = " & Speed.ToString & ", Databits=" & Databits.ToString & ", Parity=" & Parity.ToString & ", Stopbits=" & Stopbits.ToString & vbCrLf & ex.Message)
 378:              Try
 379:                  Port.Close()
 380:              Catch x As Exception
 381:                  '
 382:              End Try
 383:          End Try
 384:      End Sub
 385:   
 386:      Sub ProcessEcho()
 387:          If UserParm.Listing = UserParm.ExecListingType.Full Then
 388:              Console.WriteLine("Writing...")
 389:              Console.WriteLine(Port.ByteToString(Port.CharSet))
 390:          End If
 391:          '
 392:          Try
 393:              Port.WriteCharSetAll()
 394:          Catch ex As Exception
 395:              Console.WriteLine("Write Error: " & ex.Message)
 396:              Exit Sub
 397:          End Try
 398:          '
 399:          System.Threading.Thread.Sleep(100)
 400:          Dim Replay(Port.CharsetLength) As Byte
 401:          Try
 402:              If UserParm.Listing = UserParm.ExecListingType.Full Then
 403:                  Console.WriteLine("Reading...")
 404:              End If
 405:              Port.ComPort.Read(Replay, 0, Port.CharsetLength - 1)
 406:              Console.WriteLine(Port.ByteToString(Replay))
 407:          Catch ex As Exception
 408:              Console.WriteLine("Read Error: " & ex.Message)
 409:              Exit Sub
 410:          End Try
 411:          '
 412:          For i As Integer = 0 To Port.CharsetLength - 1
 413:              If Replay(i) <> Port.CharSet(i) Then
 414:                  Console.WriteLine("Data compare error.")
 415:                  Exit Sub
 416:              End If
 417:          Next
 418:          Console.WriteLine("Data tranfer OK.")
 419:      End Sub
 420:   
 421:      Sub ProcessModem()
 422:          Console.WriteLine("Writing AT&V...")
 423:          '
 424:          Dim Buf() As Byte
 425:          Dim ASCII As New Text.ASCIIEncoding
 426:          Buf = ASCII.GetBytes("AT&V" & vbCrLf)
 427:          Try
 428:              Port.Write(Buf)
 429:          Catch ex As Exception
 430:              Console.WriteLine("Write Error: " & ex.Message)
 431:              Exit Sub
 432:          End Try
 433:          '
 434:          Dim Replay(200) As Byte
 435:          System.Threading.Thread.Sleep(100)
 436:          Try
 437:              If UserParm.Listing = UserParm.ExecListingType.Full Then
 438:                  Console.WriteLine("Reading...")
 439:              End If
 440:              Port.ComPort.Read(Replay, 0, Math.Min(Port.ComPort.BytesToRead, Replay.Length))
 441:              Console.WriteLine(ASCII.GetString(Replay))
 442:          Catch ex As Exception
 443:              Console.WriteLine("Read Error: " & ex.Message)
 444:              Exit Sub
 445:          End Try
 446:          '
 447:      End Sub
 448:   
 449:      Sub ProcessVKP80()
 450:          VKP80_CMD.CMD_Initialize_printer()
 451:          Console.WriteLine(VKP80_CMD.GetPrinterStatus)
 452:          Port.WriteCharSetRow()
 453:          VKP80_CMD.CMDSIMPLE_Form_feed()
 454:      End Sub
 455:   
 456:  End Module

В этом статическом классе я собрал все параметры, которые должны управлять рабочими циклами:


   1:  Public Class UserParm
   2:      Public Enum ExecType
   3:          Echo = 0
   4:          Modem = 1
   5:          VKP80 = 2
   6:      End Enum
   7:      Public Enum ExecPortName
   8:          Search = 0
   9:          COM1 = 1
  10:          COM2 = 2
  11:          COM3 = 3
  12:          COM4 = 4
  13:          COM5 = 5
  14:          COM6 = 6
  15:          COM7 = 7
  16:          COM8 = 8
  17:      End Enum
  18:      Public Enum ExecSpeed
  19:          Current = 0
  20:          Search = -1
  21:          s110 = 110
  22:          s300 = 300
  23:          s1200 = 1200
  24:          s2400 = 2400
  25:          s4800 = 4800
  26:          s9600 = 9600
  27:          s19200 = 19200
  28:          s38400 = 38400
  29:          s57600 = 57600
  30:          s115200 = 115200
  31:          s230400 = 230400
  32:      End Enum
  33:      Public Enum ExecParity
  34:          Current = -2
  35:          Search = -1
  36:          None = IO.Ports.Parity.None
  37:          Odd = IO.Ports.Parity.Odd
  38:          Mark = IO.Ports.Parity.Mark
  39:          Even = IO.Ports.Parity.Even
  40:          Space = IO.Ports.Parity.Space
  41:      End Enum
  42:      Public Enum ExecDatabits
  43:          Current = -2
  44:          Search = -1
  45:          d5 = 5
  46:          d6 = 6
  47:          d7 = 7
  48:          d8 = 8
  49:      End Enum
  50:      Public Enum ExecStopBits
  51:          Current = -2
  52:          Search = -1
  53:          None = IO.Ports.StopBits.None
  54:          One = IO.Ports.StopBits.One
  55:          OnePointFive = IO.Ports.StopBits.OnePointFive
  56:          Two = IO.Ports.StopBits.Two
  57:      End Enum
  58:      Public Enum ExecTuningSleepType
  59:          Auto = 0
  60:          Manual = 1
  61:      End Enum
  62:      Public Enum ExecListingType
  63:          [Short] = 0
  64:          Full = 1
  65:      End Enum
  66:      Shared _Timeout As Integer
  67:      Public Shared Property Timeout() As Integer
  68:          Get
  69:              Return _Timeout
  70:          End Get
  71:          Set(ByVal value As Integer)
  72:              _Timeout = value
  73:          End Set
  74:      End Property
  75:      Shared _ModemCommand As String = "AT&V"
  76:      Public Shared Property ModemCommand() As String
  77:          Get
  78:              Return _ModemCommand
  79:          End Get
  80:          Set(ByVal value As String)
  81:              _ModemCommand = value
  82:          End Set
  83:      End Property
  84:      Shared _SearchType As ExecType
  85:      Public Shared Property SearchType() As ExecType
  86:          Get
  87:              Return _SearchType
  88:          End Get
  89:          Set(ByVal value As ExecType)
  90:              _SearchType = value
  91:          End Set
  92:      End Property
  93:      Shared _PortName As ExecPortName
  94:      Public Shared Property PortName() As ExecPortName
  95:          Get
  96:              Return _PortName
  97:          End Get
  98:          Set(ByVal value As ExecPortName)
  99:              _PortName = value
 100:          End Set
 101:      End Property
 102:      Shared _Speed As ExecSpeed
 103:      Public Shared Property Speed() As ExecSpeed
 104:          Get
 105:              Return _Speed
 106:          End Get
 107:          Set(ByVal value As ExecSpeed)
 108:              _Speed = value
 109:          End Set
 110:      End Property
 111:      Shared _Parity As ExecParity
 112:      Public Shared Property Parity() As ExecParity
 113:          Get
 114:              Return _Parity
 115:          End Get
 116:          Set(ByVal value As ExecParity)
 117:              _Parity = value
 118:          End Set
 119:      End Property
 120:      Shared _Databits As ExecDatabits = 8
 121:      Public Shared Property Databits() As ExecDatabits
 122:          Get
 123:              Return _Databits
 124:          End Get
 125:          Set(ByVal value As ExecDatabits)
 126:              _Databits = value
 127:          End Set
 128:      End Property
 129:      Shared _Stopbits As ExecStopBits = ExecStopBits.One
 130:      Public Shared Property Stopbits() As ExecStopBits
 131:          Get
 132:              Return _Stopbits
 133:          End Get
 134:          Set(ByVal value As ExecStopBits)
 135:              _Stopbits = value
 136:          End Set
 137:      End Property
 138:      Shared _Listing As ExecListingType = ExecListingType.Full
 139:      Public Shared Property Listing() As ExecListingType
 140:          Get
 141:              Return _Listing
 142:          End Get
 143:          Set(ByVal value As ExecListingType)
 144:              _Listing = value
 145:          End Set
 146:      End Property
 147:      Shared _TuningSleep As Integer = 100
 148:      Public Shared Property TuningSleep() As Integer
 149:          Get
 150:              Return _TuningSleep
 151:          End Get
 152:          Set(ByVal value As Integer)
 153:              _TuningSleep = value
 154:          End Set
 155:      End Property
 156:   
 157:  End Class

Этот класс - моя старинная обертка работы с COM-портом, основа работы моих многих-многих прог:


   1:  Public Class Port
   2:   
   3:      Shared _ComPort As IO.Ports.SerialPort
   4:      Public Shared ReadOnly Property ComPort() As IO.Ports.SerialPort
   5:          Get
   6:              Return _ComPort
   7:          End Get
   8:      End Property
   9:   
  10:      Public Enum Speed
  11:          s110 = 110
  12:          s300 = 300
  13:          s1200 = 1200
  14:          s2400 = 2400
  15:          s4800 = 4800
  16:          s9600 = 9600
  17:          s19200 = 19200
  18:          s38400 = 38400
  19:          s57600 = 57600
  20:          s115200 = 115200
  21:          s230400 = 230400
  22:      End Enum
  23:      Shared _ComPort_Speed As Speed = Speed.s115200
  24:      Public Shared Property ComPort_Speed() As Speed
  25:          Get
  26:              Return _ComPort_Speed
  27:          End Get
  28:          Set(ByVal value As Speed)
  29:              _ComPort_Speed = value
  30:          End Set
  31:      End Property
  32:   
  33:      Shared _ComPort_Parity As IO.Ports.Parity = IO.Ports.Parity.None
  34:      Public Shared Property ComPort_Parity() As IO.Ports.Parity
  35:          Get
  36:              Return _ComPort_Parity
  37:          End Get
  38:          Set(ByVal value As IO.Ports.Parity)
  39:              _ComPort_Parity = value
  40:          End Set
  41:      End Property
  42:   
  43:      Public Enum Databits
  44:          d5 = 5
  45:          d6 = 6
  46:          d7 = 7
  47:          d8 = 8
  48:      End Enum
  49:      Shared _ComPort_Databits As Databits = Databits.d8
  50:      Public Shared Property ComPort_Databits() As Databits
  51:          Get
  52:              Return _ComPort_Databits
  53:          End Get
  54:          Set(ByVal value As Databits)
  55:              _ComPort_Databits = value
  56:          End Set
  57:      End Property
  58:   
  59:      Shared _ComPort_StopBits As IO.Ports.StopBits = IO.Ports.StopBits.One
  60:      Public Shared Property ComPort_StopBits() As IO.Ports.StopBits
  61:          Get
  62:              Return _ComPort_StopBits
  63:          End Get
  64:          Set(ByVal value As IO.Ports.StopBits)
  65:              _ComPort_StopBits = value
  66:          End Set
  67:      End Property
  68:   
  69:      Shared _ReadTimeout As Integer = 1000
  70:      Public Shared Property ReadTimeout() As Integer
  71:          Get
  72:              Return _ReadTimeout
  73:          End Get
  74:          Set(ByVal value As Integer)
  75:              _ReadTimeout = value
  76:          End Set
  77:      End Property
  78:   
  79:      Shared _ComPortName As String
  80:      Public Shared Sub Open(ByVal ComPortName As String)
  81:          _ComPortName = ComPortName
  82:          _ComPort = My.Computer.Ports.OpenSerialPort(_ComPortName, _ComPort_Speed, _ComPort_Parity, _ComPort_Databits, _ComPort_StopBits)
  83:          _ComPort.ReadTimeout = ReadTimeout
  84:      End Sub
  85:   
  86:      Public Shared Sub Open(ByVal ComPortName As String, ByVal ComPortSpeed As Speed)
  87:          _ComPortName = ComPortName
  88:          _ComPort_Speed = ComPortSpeed
  89:          _ComPort = My.Computer.Ports.OpenSerialPort(_ComPortName, _ComPort_Speed, _ComPort_Parity, _ComPort_Databits, _ComPort_StopBits)
  90:          _ComPort.ReadTimeout = ReadTimeout
  91:      End Sub
  92:   
  93:      Public Shared Sub Open(ByVal ComPortName As String, ByVal ComPortSpeed As Speed, ByVal ComPortParity As IO.Ports.Parity)
  94:          _ComPortName = ComPortName
  95:          _ComPort_Speed = ComPortSpeed
  96:          _ComPort_Parity = ComPortParity
  97:          _ComPort = My.Computer.Ports.OpenSerialPort(_ComPortName, _ComPort_Speed, _ComPort_Parity, _ComPort_Databits, _ComPort_StopBits)
  98:          _ComPort.ReadTimeout = ReadTimeout
  99:      End Sub
 100:   
 101:      Public Shared Sub Open(ByVal ComPortName As String, ByVal ComPortSpeed As Speed, ByVal ComPortParity As IO.Ports.Parity, ByVal ComPortDatabits As Databits)
 102:          _ComPortName = ComPortName
 103:          _ComPort_Speed = ComPortSpeed
 104:          _ComPort_Parity = ComPortParity
 105:          _ComPort_Databits = ComPortDatabits
 106:          _ComPort = My.Computer.Ports.OpenSerialPort(_ComPortName, _ComPort_Speed, _ComPort_Parity, _ComPort_Databits, _ComPort_StopBits)
 107:          _ComPort.ReadTimeout = ReadTimeout
 108:      End Sub
 109:   
 110:      Public Shared Sub Open(ByVal ComPortName As String, ByVal ComPortSpeed As Speed, ByVal ComPortParity As IO.Ports.Parity, ByVal ComPortDatabits As Databits, ByVal ComPortStopBits As IO.Ports.StopBits)
 111:          _ComPortName = ComPortName : _ComPort.PortName = ComPortName
 112:          _ComPort_Speed = ComPortSpeed : _ComPort.BaudRate = ComPortSpeed
 113:          _ComPort_Parity = ComPortParity : _ComPort.Parity = ComPortParity
 114:          _ComPort_Databits = ComPortDatabits : _ComPort.DataBits = ComPortDatabits
 115:          _ComPort_StopBits = ComPortStopBits : _ComPort.StopBits = ComPortStopBits
 116:          _ComPort = My.Computer.Ports.OpenSerialPort(_ComPortName, _ComPort_Speed, _ComPort_Parity, _ComPort_Databits, _ComPort_StopBits)
 117:          _ComPort.ReadTimeout = ReadTimeout
 118:      End Sub
 119:   
 120:      Public Shared Sub Open(ByVal ComPortName As String, ByVal ComPortSpeed As Speed, ByVal ComPortParity As IO.Ports.Parity, ByVal ComPortDatabits As Databits, ByVal ComPortStopBits As IO.Ports.StopBits, ByVal ReadTimeout As Integer)
 121:          _ComPortName = ComPortName
 122:          _ComPort_Speed = ComPortSpeed
 123:          _ComPort_Parity = ComPortParity
 124:          _ComPort_Databits = ComPortDatabits
 125:          _ComPort_StopBits = ComPortStopBits
 126:          _ReadTimeout = ReadTimeout
 127:          _ComPort = My.Computer.Ports.OpenSerialPort(_ComPortName, _ComPort_Speed, _ComPort_Parity, _ComPort_Databits, _ComPort_StopBits)
 128:          _ComPort.ReadTimeout = ReadTimeout
 129:      End Sub
 130:   
 131:      Public Shared Sub Close()
 132:          _ComPort.Close()
 133:      End Sub
 134:   
 135:      Public Shared Function GetPortStatus() As String
 136:          Dim Str1 As New Text.StringBuilder
 137:          Str1.AppendLine(ComPort.PortName & " State  :")
 138:          Str1.AppendLine("----------------------------------------")
 139:          Str1.AppendLine("IsOpen                : " & ComPort.IsOpen)
 140:          Str1.AppendLine("BaudRate              : " & ComPort.BaudRate)
 141:          Str1.AppendLine("Parity                : " & ComPort.Parity)
 142:          Str1.AppendLine("DataBits              : " & ComPort.DataBits)
 143:          Str1.AppendLine("StopBits              : " & ComPort.StopBits)
 144:          Str1.AppendLine("BreakState            : " & ComPort.BreakState)
 145:          Str1.AppendLine("CDHolding             : " & ComPort.CDHolding)
 146:          Str1.AppendLine("CtsHolding            : " & ComPort.CtsHolding)
 147:          Str1.AppendLine("DsrHolding            : " & ComPort.DsrHolding)
 148:          Str1.AppendLine("RtsEnable             : " & ComPort.RtsEnable)
 149:          Str1.AppendLine("Handshake             : " & ComPort.Handshake)
 150:          Str1.AppendLine("BytesToRead           : " & ComPort.BytesToRead)
 151:          Str1.AppendLine("BytesToWrite          : " & ComPort.BytesToWrite)
 152:          Str1.AppendLine("ReadBufferSize        : " & ComPort.ReadBufferSize)
 153:          Str1.AppendLine("WriteBufferSize       : " & ComPort.WriteBufferSize)
 154:          Str1.AppendLine("Encoding              : " & ComPort.Encoding.EncodingName)
 155:          Str1.AppendLine("ReadTimeout           : " & ComPort.ReadTimeout)
 156:          Str1.AppendLine("WriteTimeout          : " & ComPort.WriteTimeout)
 157:          Str1.AppendLine("InfiniteTimeout       : " & IO.Ports.SerialPort.InfiniteTimeout)
 158:          Str1.AppendLine("DiscardNull           : " & ComPort.DiscardNull)
 159:          Str1.AppendLine("ParityReplace         : " & ComPort.ParityReplace)
 160:          Str1.AppendLine("ReceivedBytesThreshold: " & ComPort.ReceivedBytesThreshold)
 161:          Str1.AppendLine("----------------------------------------")
 162:          Return Str1.ToString
 163:      End Function
 164:   
 165:   
 166:      Public Shared Sub Write(ByVal Buf() As Byte)
 167:          _ComPort.Write(Buf, 0, Buf.Length)
 168:      End Sub
 169:   
 170:      Shared _CharSet() As Byte = {&H20, &H21, &H22, &H23, &H24, &H25, &H26, &H27, &H28, &H29, &H2A, &H2B, &H2C, &H2D, &H2E, &H2F, _
 171:                                   &H30, &H31, &H32, &H33, &H34, &H35, &H36, &H37, &H38, &H39, &H3A, &H3B, &H3C, &H3D, &H3E, &H3F, _
 172:                                   &H40, &H41, &H42, &H43, &H44, &H45, &H46, &H47, &H48, &H49, &H4A, &H4B, &H4C, &H4D, &H4E, &H4F, _
 173:                                   &H50, &H51, &H52, &H53, &H54, &H55, &H56, &H57, &H58, &H59, &H5A, &H5B, &H5C, &H5D, &H5E, &H5F, _
 174:                                   &H60, &H61, &H62, &H63, &H64, &H65, &H66, &H67, &H68, &H69, &H6A, &H6B, &H6C, &H6D, &H6E, &H6F, _
 175:                                   &H70, &H71, &H72, &H73, &H74, &H75, &H76, &H77, &H78, &H79, &H7A, &H7B, &H7C, &H7D, &H7E, &H7F, _
 176:                                   &H80, &H81, &H82, &H83, &H84, &H85, &H86, &H87, &H88, &H89, &H8A, &H8B, &H8C, &H8D, &H8E, &H8F, _
 177:                                   &H90, &H91, &H92, &H93, &H94, &H95, &H96, &H97, &H98, &H99, &H9A, &H9B, &H9C, &H9D, &H9E, &H9F, _
 178:                                   &HA0, &HA1, &HA2, &HA3, &HA4, &HA5, &HA6, &HA7, &HA8, &HA9, &HAA, &HAB, &HAC, &HAD, &HAE, &HAF, _
 179:                                   &HB0, &HB1, &HB2, &HB3, &HB4, &HB5, &HB6, &HB7, &HB8, &HB9, &HBA, &HBB, &HBC, &HBD, &HBE, &HBF, _
 180:                                   &HC0, &HC1, &HC2, &HC3, &HC4, &HC5, &HC6, &HC7, &HC8, &HC9, &HCA, &HCB, &HCC, &HCD, &HCE, &HCF, _
 181:                                   &HD0, &HD1, &HD2, &HD3, &HD4, &HD5, &HD6, &HD7, &HD8, &HD9, &HDA, &HDB, &HDC, &HDD, &HDE, &HDF, _
 182:                                   &HE0, &HE1, &HE2, &HE3, &HE4, &HE5, &HE6, &HE7, &HE8, &HE9, &HEA, &HEB, &HEC, &HED, &HEE, &HEF, _
 183:                                   &HF0, &HF1, &HF2, &HF3, &HF4, &HF5, &HF6, &HF7, &HF8, &HF9, &HFA, &HFB, &HFC, &HFD, &HFE, &HFF}
 184:   
 185:      Public Shared ReadOnly Property CharSet()
 186:          Get
 187:              Return _CharSet
 188:          End Get
 189:      End Property
 190:   
 191:      Public Shared ReadOnly Property CharsetLength() As Integer
 192:          Get
 193:              Return 224
 194:          End Get
 195:      End Property
 196:   
 197:      Public Shared Sub WriteCharSetAll()
 198:          _ComPort.Write(_CharSet, 0, _CharSet.Length)
 199:      End Sub
 200:   
 201:      Public Shared Sub WriteCharSetRow()
 202:          _ComPort.Write(vbCrLf)
 203:          For i = 0 To 13
 204:              _ComPort.Write(_CharSet, i * 16, 16)
 205:              _ComPort.Write(vbCrLf)
 206:          Next
 207:      End Sub
 208:   
 209:      Public Shared Function ByteToString(ByVal ByteArray() As Byte) As String
 210:          Dim Str1 As New Text.StringBuilder
 211:          For i As Integer = 0 To ByteArray.Length - 1
 212:              Str1.Append(String.Format("{0:X2} ", ByteArray(i)))
 213:          Next
 214:          Return Str1.ToString
 215:      End Function
 216:   
 217:   
 218:  End Class

И последний класс - это небольшой фрагмент моего OpenSource драйвера для принтеров VKP-80, который тут используется для инициализации принтера, печати состояния принтера и прошивки его набора символов:


   1:  ''' <summary>
   2:  ''' This is a small fragment of my freeware opensource driver on CUSTOM VKP80II driver http://freeware.asp-net.ru/Default.aspx?Product_ID=0d8f5276-badf-4cfb-8155-f57e8002130a
   3:  ''' </summary>
   4:  Public Class VKP80_CMD
   5:      Inherits Port
   6:   
   7:      Private Shared Function ReadStatus() As Byte()
   8:          Dim I As Integer
   9:          Dim Y() As Byte = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
  10:          For I = 0 To Y.Length - 1
  11:              Y(I) = 0
  12:          Next
  13:          For I = 0 To Y.Length - 1
  14:              'ключевое местечко - время задержки подобрано опытным путем
  15:              System.Threading.Thread.Sleep(100)
  16:              If ComPort.BytesToRead > 0 Then
  17:                  Y(I) = CByte(ComPort.ReadByte)
  18:              Else
  19:                  Exit For
  20:              End If
  21:          Next
  22:          ReDim Preserve Y(I - 1)
  23:          Return Y
  24:      End Function
  25:   
  26:      Public Shared Function GetPrinterStatus() As String
  27:          Dim Str1 As New Text.StringBuilder
  28:          Str1.AppendLine("VKP80II State  :")
  29:          Str1.AppendLine("----------------------------------------")
  30:          Str1.AppendLine("FullStatus     : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Realtime_status_transmission(VKP80_CMD.RequestType.FullStatus)))
  31:          Str1.AppendLine("ErrorStatus    : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Realtime_status_transmission(VKP80_CMD.RequestType.ErrorStatus)))
  32:          Str1.AppendLine("PrinterStatus  : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Realtime_status_transmission(VKP80_CMD.RequestType.PrinterStatus)))
  33:          Str1.AppendLine("PrintStatus    : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Realtime_status_transmission(VKP80_CMD.RequestType.PrintStatus)))
  34:          Str1.AppendLine("OfflineStatus  : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Realtime_status_transmission(VKP80_CMD.RequestType.OfflineStatus)))
  35:          Str1.AppendLine("RollSensor     : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Realtime_status_transmission(VKP80_CMD.RequestType.PaperRollSensorStatus)))
  36:          Str1.AppendLine("EjectorSensor  : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Ejector_commands(6)))
  37:          Str1.AppendLine("PaperEndSensor : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Transmit_status(1)))
  38:          Str1.AppendLine("PrinterID1     : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Transmit_printer_ID(1)))
  39:          Str1.AppendLine("PrinterID2     : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Transmit_printer_ID(2)))
  40:          Str1.AppendLine("PrinterID3     : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Transmit_printer_ID(3)))
  41:          Str1.AppendLine("Cuts           : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Reading_number_of_cuts_performed_from_the_printer))
  42:          Str1.AppendLine("PowerUp        : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Reading_number_of_power_up))
  43:          Str1.AppendLine("Retracting     : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Reading_number_of_retracting))
  44:          Str1.AppendLine("PaperLength1   : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Reading_of_length_cm_of_printed_paper))
  45:          Str1.AppendLine("PaperLength2   : " & VKP80_CMD.ByteToString(VKP80_CMD.CMDSTATUS_Reading_of_length_paper_cm_available_before_virtual_paper_end))
  46:          Str1.AppendLine("----------------------------------------")
  47:          Return Str1.ToString
  48:      End Function
  49:   
  50:  #Region "Статусы принтера и статистика"
  51:   
  52:      'Printer Sensor:
  53:      '1. Head temperature
  54:      '2. Black mark
  55:      '3. Paper end
  56:      '4. Ticket presence on output
  57:      '5. Opening of printing unit
  58:      '6. Near paper end on roll support is optional
  59:      'Public Overloads Shared Function _CMD_Ejector_commands()
  60:   
  61:      ''' <summary>
  62:      ''' Near paper-end sensor and Paper-end sensor
  63:      ''' </summary>
  64:      Shared Function CMDSTATUS_Transmit_parer_sensor_status() As Byte()
  65:          Dim X() As Byte = {&H1B, &H76}
  66:          Port.Write(X)
  67:          Return ReadStatus()
  68:      End Function
  69:   
  70:      ''' <summary>
  71:      ''' Near paper-end sensor and Paper-end sensor
  72:      ''' </summary>
  73:      ''' <param name="n">n = 1, 49</param>
  74:      Shared Function CMDSTATUS_Transmit_status(ByVal n As Integer) As Byte()
  75:          Dim X() As Byte = {&H1D, &H72, CByte(n)}
  76:          Port.Write(X)
  77:          Return ReadStatus()
  78:      End Function
  79:   
  80:      ''' <summary>
  81:      ''' Transmits the printer ID speci?ed by n follows
  82:      ''' </summary>
  83:      ''' <param name="n">1 ? n ? 3, 49 ? n ? 51</param>
  84:      Shared Function CMDSTATUS_Transmit_printer_ID(ByVal n As Integer) As Byte()
  85:          Dim X() As Byte = {&H1D, &H49, CByte(n)}
  86:          Port.Write(X)
  87:          Return ReadStatus()
  88:      End Function
  89:   
  90:      ''' <summary>
  91:      ''' Transmits the selected printer status speci?ed by n in real time according to the following parameters:
  92:      ''' n = 1 transmit printer status
  93:      ''' n = 2 transmit off-line status
  94:      ''' n = 3 transmit error status
  95:      ''' n = 4 transmit paper roll sensor status
  96:      ''' n = 17 transmit print status
  97:      ''' n = 20 transmit FULL STATUS
  98:      ''' This command is executed when the data buffer is full.
  99:      ''' This status is transmitted whenever data sequence $10 $04 n is received.
 100:      ''' </summary>
 101:      ''' <param name="n">1 ? n ? 4; n=17, n=20</param>
 102:      Public Shared Function CMDSTATUS_Realtime_status_transmission(ByVal n As Integer) As Byte()
 103:          Dim X() As Byte = {&H10, &H4, CByte(n)}
 104:          Port.Write(X)
 105:          Return ReadStatus()
 106:      End Function
 107:   
 108:      Public Enum RequestType
 109:          PrinterStatus = 1
 110:          OfflineStatus = 2
 111:          ErrorStatus = 3
 112:          PaperRollSensorStatus = 4
 113:          PrintStatus = 17
 114:          FullStatus = 20
 115:      End Enum
 116:   
 117:      Public Shared Function CMDSTATUS_Realtime_status_transmission(ByVal Request As RequestType) As Byte()
 118:          Return VKP80_CMD.CMDSTATUS_Realtime_status_transmission(CInt(Request))
 119:      End Function
 120:   
 121:      ''' <summary>
 122:      ''' This command handles tickets ejector:
 123:      ''' n = 1 
 124:      ''' n = 2 Execute a ticket retract (only if Paper retracting is enabled)
 125:      ''' n = 3 Produce a ticket with m steps (1 step = 7.3 mm)
 126:      ''' n = 5 Eject ticket
 127:      ''' n = 6 Transmit the status byte of the ejector
 128:      ''' </summary>
 129:      Shared Function CMDSTATUS_Ejector_commands(ByVal n As Integer, ByVal m As Integer) As Byte()
 130:          Dim X() As Byte = {&H1D, &H65, CByte(n), CByte(m)}
 131:          Port.Write(X)
 132:          Return ReadStatus()
 133:      End Function
 134:   
 135:      Shared Function CMDSTATUS_Ejector_commands(ByVal n As Integer) As Byte()
 136:          Dim X() As Byte = {&H1D, &H65, CByte(n)}
 137:          Port.Write(X)
 138:          Return ReadStatus()
 139:      End Function
 140:   
 141:      ''' <summary>
 142:      ''' Reading of length (cm) paper available before virtual paper-end.
 143:      ''' The command return a string pointing out how much paper is available, for example if there are 5.1 m before the paper end, it will be: ‘510cm’
 144:      ''' • The lenght of residual paper reported is just as an indication because tolerances and other factors are not taken into consideration (paper thickness, roll core diameter, roll core thickness). The virtual paper-end limit is set by the command $1D $E6.
 145:      ''' • To set virtual paper-end limit, measure the length of the paper from near paper end to the end of the roll, using several of them.
 146:      ''' </summary>
 147:      Shared Function CMDSTATUS_Reading_of_length_paper_cm_available_before_virtual_paper_end() As Byte()
 148:          Dim X() As Byte = {&H1D, &HE1}
 149:          Port.Write(X)
 150:          Return ReadStatus()
 151:      End Function
 152:      ''' <summary>
 153:      ''' The command return a string that points out how many cuts are performed by the printer, for example if there are performed 2376 cuts, it will be: ‘2376 cuts’
 154:      ''' </summary>
 155:      Shared Function CMDSTATUS_Reading_number_of_cuts_performed_from_the_printer() As Byte()
 156:          Dim X() As Byte = {&H1D, &HE2}
 157:          Port.Write(X)
 158:          Return ReadStatus()
 159:      End Function
 160:      ''' <summary>
 161:      ''' The command return a string pointing out how much paper is printed, for example if the printer has print about 2515,5 m, it will be: ‘251550cm’
 162:      ''' </summary>
 163:      Shared Function CMDSTATUS_Reading_of_length_cm_of_printed_paper() As Byte()
 164:          Dim X() As Byte = {&H1D, &HE3}
 165:          Port.Write(X)
 166:          Return ReadStatus()
 167:      End Function
 168:      ''' <summary>
 169:      ''' • The command return a string pointing out the number of retracting of the printer, for example if the printer has retracted the paper 512 times, it will be: ‘512ret’
 170:      ''' </summary>
 171:      Shared Function CMDSTATUS_Reading_number_of_retracting() As Byte()
 172:          Dim X() As Byte = {&H1D, &HE4}
 173:          Port.Write(X)
 174:          Return ReadStatus()
 175:      End Function
 176:      ''' <summary>
 177:      ''' Reading number of power up of the printer.
 178:      ''' • The command return a string pointing out the number of turning on of the printer, for example if the printer is turned on 512 times, it will be: ‘512on’
 179:      ''' </summary>
 180:      Shared Function CMDSTATUS_Reading_number_of_power_up() As Byte()
 181:          Dim X() As Byte = {&H1D, &HE5}
 182:          Port.Write(X)
 183:          Return ReadStatus()
 184:      End Function
 185:   
 186:  #End Region
 187:   
 188:      ''' <summary>
 189:      ''' Clears the data in the print buffer and resets the printer mode to that in effect when power was turned on.
 190:      ''' • The data in the receiver buffer is not cleared.
 191:      ''' • The macro de?nitions are not cleared.
 192:      ''' </summary>
 193:      Shared Sub CMD_Initialize_printer()
 194:          Dim X() As Byte = {&H1B, &H40}
 195:          Port.Write(X)
 196:      End Sub
 197:   
 198:  #Region "Простейшие команды"
 199:   
 200:      ''' <summary>
 201:      ''' Moves print position to previous character
 202:      ''' </summary>
 203:      Shared Sub CMDSIMPLE_Back_space()
 204:          Dim X() As Byte = {&H8}
 205:          Port.Write(X)
 206:      End Sub
 207:      ''' <summary>
 208:      ''' Ignored unless the next horizontal tab position has been set
 209:      ''' If the command is received when the printing position is at the right margin, 
 210:      ''' the printer executes print buffer full printing and horizontal tab processing from the beginning of the  next line. 
 211:      '''</summary>
 212:      Shared Sub CMDSIMPLE_Horizontal_tab()
 213:          Dim X() As Byte = {&H9}
 214:          Port.Write(X)
 215:      End Sub
 216:      ''' <summary>
 217:      ''' Sets the print position to the beginning of the line
 218:      ''' </summary>
 219:      Shared Sub CMDSIMPLE_Print_and_line_feed()
 220:          Dim X() As Byte = {&HA}
 221:          Port.Write(X)
 222:      End Sub
 223:      ''' <summary>
 224:      ''' Prints the data in the buffer, cuts the paper and presents the ticket.
 225:      ''' </summary>
 226:      Shared Sub CMDSIMPLE_Form_feed()
 227:          Dim X() As Byte = {&HC}
 228:          Port.Write(X)
 229:      End Sub
 230:      ''' <summary>
 231:      ''' Sets the print position to the beginning of the line.  See “Autofeed in setup” parameter.
 232:      ''' When autofeed is “CR enabled”, this command functions in the same way as $0A, otherwise it is disregarded.
 233:      ''' </summary>
 234:      Shared Sub CMDSIMPLE_Print_and_carriage_return()
 235:          Dim X() As Byte = {&HD}
 236:          Port.Write(X)
 237:      End Sub
 238:   
 239:   
 240:  #End Region
 241:   
 242:   
 243:  End Class


Комментарии к этой страничке ( )
ссылка на эту страничку: http://www.vb-net.ru/ComDetector/index.htm
<На главную>  <В раздел ASP>  <В раздел NET>  <В раздел SQL>  <В раздел Разное>  <Написать автору>  < Поблагодарить>