;;; -*- Mode:LISP; Package:LAMBDA -*-
;;;
;;; (c) Copyright 1984 - Lisp Machine, Inc.
;;;


;;this file contains the code for handling serial communications to an sdu, causing
;;it to perform bus cycles and special diagnostic functions on a remote nubus

(defun write-msg (address data)
  (let (msg)
     (setq msg (format nil "w~A ~o ~o%" (ascii 0) address data))
     (aset (compute-checksum msg) msg 2)
     (format serial-stream msg)))

(defun read-msg (address)
   (let (msg chr checksumchr messagebody)

      ; send the message, which should have format "r<checksum>....<CR>"
      (setq msg (format nil "r~A ~o%" (ascii 0) address))
      (aset (compute-checksum msg) msg 2)
      (format serial-stream msg)

      ; read the response, which should have format "R<checksum>....<CR>"
      (setq chr (readch serial-stream))
      (cond ((neq chr (character #\R))
	     (format nil "Read bad message key from serial stream ~A%" chr)))
      (setq checksumchr (readch serial-stream))
      (setq messagebody (readline serial-stream))
      (cond ((neq (compute-checksum (string-append chr messagebody (format nil "%")))
		  checksumchr)
	     (format t "Message has bad checksum.%")))))


     

(defun compute-checksum (str)
   (loop for x from 0 to (1- (string-length str))
         sum (aref str x) into chr-sum
         finally (return (remainder chr-sum 128.))))
