Attachment 'hp1652_ser.py'

Download

   1 #! /usr/bin/env python
   2 """
   3 # hp1652_ser.py - Utility program for HP1652B connected to RS232 port.
   4 # already implemented:
   5 #   IDN = Identity
   6 #   print screen with Date & Time overlay
   7 #   Printer Type default: HP Thinkjet
   8 #   more to come ...
   9 # Print All can be captured by Mac OS CoolTerm.app
  10 #
  11 # 2011-07-14 RudolfReuter, written for HP1631D
  12 # 2011-12-05 RudolfReuter, default is "print" (-pv)
  13 # 2014-02-25 RudolfReuter, .gif file because of "converter", .png has bad quality
  14 # 2015-02-08 RudolfReuter, serial port selection by OS platform.
  15 # 2016-08-17 RudolfReuter, fix for pyserial DTR toggle, that gives an Arduino RESET
  16 # 2016-06-16 RudolfReuter, V1.2, serial port timeout set to 1 second
  17 # 2018-03-11 RR, serial1->serial0
  18 # 2020-05-02 RR, corrected Windows port, Thanks to Joe
  19 """
  20 
  21 import array
  22 import glob
  23 import optparse
  24 import os
  25 import serial
  26 import subprocess
  27 import sys
  28 import time
  29 import platform
  30 
  31 # on which port should the tests be performed
  32 # http://sourceforge.net/projects/osx-pl2303/
  33 
  34 LINEFEED = '\x0A'   # CTRL+J
  35 ESC = '\x1B'
  36 
  37 def scan():
  38     """scan for available ports. return a list of device names."""
  39     return glob.glob('/dev/cu.*')
  40 
  41 def ser_answer():
  42     """Read the answer after sending a command to the USB-GPIB converter."""
  43     answer = ser.read(30)
  44     if options.verbose:
  45         if (len(answer) == 1):
  46             print "Answer: {0:#04X}".format(ord(answer))
  47         elif (len(answer) > 1):
  48             print "Answer: " + answer
  49     if (len(answer) > 1):
  50         if "Error 1" in answer:
  51             print "GBIP Device (Address) not found"
  52         elif "Error 2" in answer:
  53             print "GPIB Timeout Error"
  54         else:
  55             print answer
  56         ser.close()
  57         sys.exit(6)
  58 
  59 if __name__=='__main__':
  60 
  61     os_name = platform.system()
  62     if os_name == "Windows":
  63         port = "COM1:"
  64     if os_name == "Linux":
  65         port = "/dev/ttyS0"
  66     if os_name == "Darwin":
  67         port = "/dev/cu.serial0"
  68     # for use with IDLE, command line argument, BUT "convert" does NOT work in IDLE
  69     #sys.argv = ['hp1652.py_ser', '-pv']
  70     apath = os.getcwd()
  71     print (apath)
  72     
  73     parser = optparse.OptionParser(
  74         usage = "%prog [options] [port [baudrate]] version 1.2", 
  75         description = "hp1652 - A converter hardcopy to PBM."
  76     )
  77     parser.add_option("-a", "--printall", dest="printall", action="store_true",
  78                       help="print all")
  79     parser.add_option("-b", "--beep", dest="beep", action="store_true",
  80                       help="actuate GPIB device beep")
  81     parser.add_option("-d", "--date", dest="date", action="store_true",
  82                       help="set date to hp1630")
  83     parser.add_option("-f", "--file", dest="filename",
  84                       help="Enter filename")
  85     parser.add_option("-g", "--gport", dest="gport",
  86                       help="serial port, e.g. /dev/cu.xxx")
  87     parser.add_option("-i", "--id", action="store_true", dest="id",
  88                       help="check for GPIB device ID")
  89     parser.add_option("-l", "--local", action="store_true", dest="local",
  90                       help="switch GPIB device to local mode")
  91     parser.add_option("-p", "--print", dest="printWS", action="store_true",
  92                       help="print screen in PBM format")
  93     #parser.add_option("-q", "--quiet",
  94     #                  action="store_false", dest="verbose", default=True,
  95     #                  help="don't print status messages to stdout")
  96     parser.add_option("-r", "--restore", action="store_true", dest="restore",
  97                       help="restore Learn String File, enter Filename with -f")
  98     parser.add_option("-t", "--timeout", dest="timeout",
  99                       help="Enter timeout in sec.")
 100     parser.add_option("-u", "--usb", action="store_true", dest="usb",
 101                       help="check for USB-GPIB interface")
 102     parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
 103                       help="tell more internal values for debugging")
 104 
 105     (options, args) = parser.parse_args()
 106 
 107     if (len(sys.argv) < 2):  # no arguments given
 108         parser.print_help()
 109         print "Default Serial Port: " + port
 110 
 111 # open USB-serial port
 112     if options.gport:
 113         port = options.gport
 114     otimeout = 60              # 60 sec
 115     if options.timeout:
 116         otimeout = int(options.timeout)
 117     try:
 118         otimeout = 1           # 1 sec
 119         ser = serial.Serial(port, baudrate=9600, timeout=otimeout)
 120         if options.verbose:
 121             print ser.name
 122         ser.flushInput()
 123         time.sleep(1.5)  # fix for Arduino DTR toggle RESET
 124     except serial.SerialException, e:
 125         sys.stderr.write("could not open port %r: %s\n" % (port, e))
 126         print "Found ports:"
 127         for name in scan():
 128             print "  "+name
 129         sys.exit(1)
 130 
 131     if options.printall:
 132         fname = "printall.txt"
 133         if options.filename:
 134             fname = options.filename
 135         # read pint screen from List Menu
 136         ser.write("E4,LM;CD;PA\n")
 137         hello = ser.read(1) # skip LineFeed, if there
 138         screen = ser.read(100000)
 139         #if screen[0] == "*":  # LineFeed was not there
 140         #    screen = TAB + screen
 141         if (len(screen) < 1000):
 142             print "len too short: " + str(len(screen))
 143             ser.write("B4,1\n") # Go To Local
 144             ser_answer()
 145             ser.close
 146             sys.exit(2)
 147         if options.verbose:
 148             print len(screen)
 149         # write text file
 150         try:
 151             f = file(fname, 'w')
 152             f.write(screen)
 153             f.close()
 154         except IOError, e:
 155             sys.stderr.write('ERROR opening file %s: %s \n' % (fname_tmp, e))
 156             ser.close()
 157             sys.exit(3)
 158         # Go To Local
 159         ser.write("B4,1\n")
 160         ser_answer() 
 161         
 162     if options.beep:
 163         if options.verbose:
 164             print "Beep"
 165 #        ser.write("W4,BP\n")
 166 #        ser_answer()
 167         # Go To Local
 168 #        ser.write("B4,1\n")
 169 #        ser_answer()
 170         
 171     if options.date:
 172         # Set date and time
 173         now = time.strftime('%m%d%Y%H%M%S')
 174         if options.verbose:
 175             print now
 176         month = int(now[0:2])
 177         datestr = now[2:]
 178         ser.write("W4,SM;NX;CD;CE\n")
 179         ser_answer()
 180         if month > 1:
 181                 ser.write("W4,NX"+str(month-1)+"\n")
 182                 ser_answer()  
 183         ser.write('W4,CR;"'+datestr+'"\n')
 184         ser_answer()
 185         # Go To Local
 186         ser.write("B4,1\n")
 187         ser_answer()
 188 
 189     if options.id:
 190         if options.verbose:
 191             print "*IDN?"
 192         ser.write("*IDN?\n")
 193         hello = ser.read(40)
 194         print hello
 195         # Go To Local
 196 #        ser.write("B4,1\n")
 197 #        ser_answer()
 198 
 199     if options.local:
 200         if options.verbose:
 201             print "Go To Local"
 202         ser.write("B4,1\n")
 203         ser_answer()
 204 
 205     if options.printWS:
 206         fname = "hardcopy"
 207         fname_tmp = "HP1652_hc.hpg"
 208         if options.verbose:
 209             print "Temporary file: " + fname_tmp
 210         
 211         # read pint screen
 212 #        ser.write(":SYSTEM:PRINT SCREEN\n")  # does not work!
 213         print ("Press button I/O and select 'Print screen' within 30 sec.")
 214         i = 0
 215         while (i < 30):            # wait up to 30 sec.
 216             hello = ser.read(2)    # skip CR/LF
 217             if (len(hello) < 1):   # It was a timeout
 218                 i += 1
 219                 sys.stdout.write(str(i))
 220             else:
 221                 screen = ser.read(50000)
 222                 break
 223             print                  # CR+LF
 224 #        if screen[0] == "*":  # LineFeed was not there
 225 #            screen = ESC + screen
 226         if (len(screen) < 1000):
 227             print "len too short: " + str(len(screen))
 228             ser.close
 229             sys.exit(2)
 230         if options.verbose:
 231             print len(screen)
 232         # write temporary file
 233         try:
 234             f = file(fname_tmp, 'wb')
 235             f.write(screen)
 236             f.close()
 237         except IOError, e:
 238             sys.stderr.write('ERROR opening file %s: %s \n' % (fname_tmp, e))
 239             ser.close()
 240             sys.exit(3)     
 241         
 242         cur_row = 0
 243         width = -1
 244         gr_data = array.array('c')
 245 
 246         try:
 247             f = file(fname_tmp, 'rb')  # read binary
 248             statinfo = os.stat(fname_tmp)
 249             fdate = time.strftime('%Y-%m-%d %H%:%M:%S', time.localtime(statinfo.st_mtime))
 250             if options.verbose:
 251                 print fdate
 252 
 253             buf = f.read(11)  # read header ??? ValueError: I/O operation on closed file
 254             if (buf[1:6] != "*r640"):
 255                 print ("Header" + buf[1:6])
 256                 f.close()
 257                 sys.exit(1)
 258             while (1):
 259                 buf = f.read(6)
 260                 if (buf[2:4] == "rB"):  # end of graphic
 261                     break
 262                 w = int(buf[3:5])  # line byte width
 263                 if (width == -1):
 264                     width = w
 265                 gr_data.fromfile(f, width)
 266                 cur_row += 1
 267                 #if (cur_row%10 == 0): print cur_row
 268 
 269             if options.verbose:
 270                 print "Bitmap geometry x, y: " + str(width*8) + " " + str(cur_row)
 271             f.close()
 272         except IOError, e:
 273             sys.stderr.write('ERROR opening file %s: %s \n' % (fname_tmp, e))
 274             ser.close()
 275             sys.exit(4)
 276         # write PBM file
 277         # Def: http://en.wikipedia.org/wiki/Netpbm_format
 278         #f = file(fname[0:-3] + 'pbm', 'wb')  # write binary
 279         try:
 280             f = file(fname + '.pbm', 'wb')  # write binary
 281             f.write('P4\n')                 # write Header
 282             f.write("# from HP1652, " + fdate + "\n")
 283             f.write(str(width*8) + " " + str(cur_row) + "\n")
 284             gr_data.tofile(f)
 285             f.close()
 286         except IOError, e:
 287             sys.stderr.write('ERROR opening file %s: %s \n' % (fname, e))
 288             ser.close()
 289             sys.exit(4)
 290         # Insert date & time with ImageMagick convert
 291         shellstr = "convert -font helvetica -pointsize 12 -fill white -draw "
 292         shellstr = shellstr + '"rectangle 390,0 575,30" -fill black -draw '
 293         shellstr = shellstr + '"text 400, 12 ' + "'`date`'" + '" '
 294         shellstr = shellstr + fname + '.pbm' + " " + fname + '.gif'
 295         if options.verbose:
 296             print (shellstr)
 297             print ("Note: 'convert' does NOT work in IDLE!")
 298         try:
 299             #os.system(shellstr)
 300             retcode = subprocess.call(shellstr, shell=True)
 301         except OSError, e:
 302             sys.stderr.write('ERROR convert file %s \n' % (e))
 303             ser.close()
 304             sys.exit(4)
 305 
 306     if options.restore:
 307         # Restore reverse assembler
 308         #revasm = 'IHPIBi2.bin'
 309         revasm = options.filename
 310         if options.verbose:
 311             print "File Reverse Assembler: " + revasm
 312         try:
 313             f = file(revasm, 'r')
 314             resbuf = f.read(10000)
 315             f.close()
 316             if options.verbose:
 317                 print len(resbuf)
 318                 print resbuf[0:2]
 319         except IOError, e:
 320             sys.stderr.write('ERROR opening file %s: %s \n' % (revasm, e))               
 321 
 322         # setup Listerner
 323         ser.write("L4,\n")
 324         ser_answer()
 325 
 326         # Output data
 327         for i in range(0, len(resbuf)):
 328             ser.write("D"+"\n"+resbuf[i])
 329             hello = ser.read(1)
 330             if len(hello) == 0:
 331                 print "i=" + str(i)
 332                 break
 333             if (resbuf[i] != hello):
 334                 print "Error compare buf 0x%X ret 0x%X  i=%d" % (ord(resbuf[i]), ord(hello), i)
 335             #print hello
 336             
 337         # End transmittion with LF+EOI+UNL+UNT
 338         ser.write("U\n")
 339         ser_answer()
 340         
 341     if options.usb:
 342         ser.write("I\n")
 343         if options.verbose:
 344             print "Output I, expect answer: GPIB/USB converter V1.1"
 345         hello = ser.read(30)
 346         if (len(hello) < 10):
 347             print "R8C/13 USB-GPIB interface is not available"
 348             ser.close()
 349             sys.exit()
 350         else:       
 351             print hello
 352 
 353 ser.close()

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2013-05-08 04:53:00, 6.4 KB) [[attachment:HP1652_GPIB_InvAsm.png]]
  • [get | view] (2013-05-08 04:53:00, 5.7 KB) [[attachment:HP1652_GPIB_InvAsmO.png]]
  • [get | view] (2013-05-08 04:53:00, 71.3 KB) [[attachment:HP1652_GPIB_TimeDSC01721.jpg]]
  • [get | view] (2013-05-08 04:53:00, 84.3 KB) [[attachment:HP1652_SFORM_GPIB_DSC01719.jpg]]
  • [get | view] (2013-05-08 04:53:00, 2.1 KB) [[attachment:IHPIB1.R]]
  • [get | view] (2017-05-28 13:40:00, 7.8 KB) [[attachment:IHPIB1.S]]
  • [get | view] (2013-05-08 04:53:00, 18.0 KB) [[attachment:IHPIB1.TXT]]
  • [get | view] (2013-05-08 04:53:00, 5.4 KB) [[attachment:State_Format_GPIB.png]]
  • [get | view] (2013-05-08 04:53:00, 10.8 KB) [[attachment:hp1652.py]]
  • [get | view] (2020-05-02 03:30:47, 11.9 KB) [[attachment:hp1652_ser.py]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.