Esempio n. 1
0
    def __init__(self, port, baund=9600):

        self.sendbuf = Zkzt2_ST(code, addr)  #定义发送结构体
        self.recvbuf = Zkzt2_ST()  #定义接收结构体

        self.ser = SerialPort(port, baund)  #初始化串口
        self.ser.open()  #打开串口
Esempio n. 2
0
    def __init__(self, port, baund=9600):
        self.rcflg = 0  #接收成功标识
        self.rcbuf = PcComInfo(0, 0, 0)  #接收数据

        self.ser = SerialPort(port, baund)  #初始化串口
        self.ser.open()  #打开串口
        pcThread = threading.Thread(target=self.ser.recv)  #创建多线程,启动接收任务
        pcThread.start()
Esempio n. 3
0
 def __init__(self):
     self.login = MainApp()
     self.cpuThread = QThread()
     self.scannerThread = QThread()
     self.open_admin = False
     self.open_user = False
     self.open_stats = False
     self.cpu = SerialPort('CPU')
     self.scanner = SerialPort('Scanner')
     self.cpu.moveToThread(self.cpuThread)
     self.scanner.moveToThread(self.scannerThread)
Esempio n. 4
0
 def checkMode(self):
     inputTxt = []
     inputTxt.append('MD')
     serialportObj = SerialPort.SerialConnection()
     ser = serialportObj.open_connection()
     outTxt = serialportObj.serialIO(inputTxt, ser)
     return (outTxt)
Esempio n. 5
0
    def __init__(self, sync_event, spike_listener, position_estimator,
                 place_field_handler):
        """TODO: to be defined1. """
        ThreadExtension.StoppableProcess.__init__(self)
        self._sync_event = sync_event
        self._spike_buffer = collections.deque(maxlen=self._SPIKE_BUFFER_SIZE)
        self._spike_histogram = collections.Counter()
        self._spike_buffer_connection = spike_listener.get_spike_buffer_connection(
        )
        self._position_buffer_connection = position_estimator.get_position_buffer_connection(
        )
        self._place_field_handler = place_field_handler
        self._position_access = Lock()
        self._spike_access = Lock()
        # TODO: This functionality should be moved to the parent class
        self._enable_synchrnoizer = Lock()
        self._is_disabled = Value("b", True)

        # Position data at the time ripple is triggered
        self._pos_x = -1
        self._pos_y = -1
        self._most_recent_speed = 0
        self._most_recent_pos_timestamp = 0
        self._serial_port = None
        try:
            self._serial_port = SerialPort.BiphasicPort()
        except Exception as err:
            logging.warning("Unable to open Serial port.")
            print(err)
        logging.info(self.CLASS_IDENTIFIER +
                     "Started Ripple Synchronization thread.")
Esempio n. 6
0
 def scanMode(self):
     inputTxt = []
     inputTxt.append('KEY00')
     serialportObj = SerialPort.SerialConnection()
     ser = serialportObj.open_connection()
     serialportObj.serialIO(inputTxt, ser)
     return None
Esempio n. 7
0
def main():
    global task_end_flag, task, DEBUG, task_running

    detector = Detector()

    with SerialPort('/dev/serial0', 9600, None) as sp:
        while True:
            if sp.receiveData():
                # 复位检测器
                detector.reset()
                try:
                    detect_type = sp.getReceive()['byte'][0]
                    if DEBUG:
                        print(detect_type)
                    # 等待
                    if detect_type == 0:
                        if task is not None and task_running:
                            task_end_flag = True
                            task.join()
                            task_end_flag = False
                        task = Thread(target=waiting)
                        task.start()
                    # 3数字二维码
                    if detect_type == 1:
                        if task is not None and task_running:
                            task_end_flag = True
                            task.join()
                            task_end_flag = False
                        task = Thread(target=detect_qrcode, args=[detector, sp,])
                        task.start()
                    # 3色块
                    elif detect_type == 2:
                        if task is not None and task_running:
                            task_end_flag = True
                            task.join()
                            task_end_flag = False
                        task = Thread(target=detect_color, args=[detector, sp,])
                        task.start()
                    # 3+3数字二维码
                    elif detect_type == 3:
                        if task is not None and task_running:
                            task_end_flag = True
                            task.join()
                            task_end_flag = False
                        task = Thread(target=detect_qrcode, args=[detector, sp, 1])
                        task.start()
                    # 3颜色条形码
                    elif detect_type == 4:
                        if task is not None and task_running:
                            task_end_flag = True
                            task.join()
                            task_end_flag = False
                        task = Thread(target=detect_qrcode, args=[detector, sp, 2])
                        task.start()
                except:
                    pass
            else:
                if not task_running and DISPLAY:
                    task = Thread(target=display)
                    task.start()
Esempio n. 8
0
    def viewScannerChannel(self, channelNum):
        self.__channelNum = channelNum

        channelNumPadded = str("{0:0>3}".format(channelNum))
        #print(channelNumPadded)
        inputTxt = []
        #inputTxt.append('MA' + channelNumPadded)
        inputTxt.append('PM' + channelNumPadded)  # Print Memory Data
        #ser=sc.serObj(sc)
        serialportObj = SerialPort.SerialConnection()
        ser = serialportObj.open_connection()
        outTxt = serialportObj.serialIO(inputTxt, ser)
        #channelTxt = ''
        #channelTxt = 'Freq: ' + outTxt[6:10] + '.' + outTxt[10:14] + 'MHz'
        #channelTxt = ''
        #outTxtFreq = outTxt[6:14]
        #return(channelTxt.join(outTxtFreq))
        #return(outTxt, channelTxt)
        outTxtFreq = outTxt
        #outTxtFreq = outTxt[1:33]
        #outTxtFreq = outTxt[6:14] # Just grab frequency
        # list comprehension. Turns list to string.
        # Works for list with mixed element types (if applicable)
        channelTxt = ''.join([str(element) for element in outTxtFreq])
        #print(channelTxt)
        return channelTxt
Esempio n. 9
0
 def manualMode(self):
     inputTxt = []
     inputTxt.append('KEY01')
     serialportObj = SerialPort.SerialConnection()
     ser = serialportObj.open_connection()
     serialportObj.serialIO(inputTxt, ser)
     scanner.freq_display()
     return None
Esempio n. 10
0
class Zkzt2Data:
    def __init__(self, port, baund=9600):

        self.sendbuf = Zkzt2_ST(code, addr)  #定义发送结构体
        self.recvbuf = Zkzt2_ST()  #定义接收结构体

        self.ser = SerialPort(port, baund)  #初始化串口
        self.ser.open()  #打开串口

        #pcThread = threading.Thread(target = self.ser.recv)     #创建多线程,启动接收任务
        #pcThread.start()

    def stop(self):
        self.sendbuf.status = STA_STOP
        self.sendbuf.bcc = Checker.GetBccCheck(ctypes.byref(self.sendbuf),
                                               ctypes.sizeof(Zkzt2_ST) - 1)

        print(self.sendbuf.status, self.sendbuf.bcc)
        self.ser.send(self.sendbuf)

    def setSpeed(self, speed, frq=1000, direction=STA_CW):
        self.sendbuf.status = direction  #设置状态,默认正转
        self.sendbuf.speedH = 0x00
        self.sendbuf.speedL = speed
        print(frq, frq >> 8, frq)
        self.sendbuf.frqH = frq >> 8
        self.sendbuf.frqL = frq

        self.sendbuf.bcc = Checker.GetBccCheck(ctypes.byref(self.sendbuf),
                                               ctypes.sizeof(Zkzt2_ST) - 1)

        print(self.sendbuf.status, self.sendbuf.bcc)
        self.ser.send(self.sendbuf)
Esempio n. 11
0
class PcComm:
    def __init__(self, port, baund=9600):
        self.rcflg = 0  #接收成功标识
        self.rcbuf = PcComInfo(0, 0, 0)  #接收数据

        self.ser = SerialPort(port, baund)  #初始化串口
        self.ser.open()  #打开串口
        pcThread = threading.Thread(target=self.ser.recv)  #创建多线程,启动接收任务
        pcThread.start()

    def recvThread(self):
        while True:
            time.sleep(0.2)  #循环周期

            if (self.ser.recv_len):  #数据接收成功

                Crc.GetCheckSum.restype = c_uint8  #GetCheckSum 返回值类型
                crc = Crc.GetCheckSum(self.ser.recv_buf,
                                      self.ser.recv_len - 1)  #计算校验和

                #print(self.ser.recv_buf)
                #print(crc,self.ser.recv_buf[self.ser.recv_len-1])
                if (crc == self.ser.recv_buf[self.ser.recv_len - 1]):  #校验正确
                    self.ser.send(send_buf)  #发送应答,标识接收正常
                    #self.rcbuf = self.ser.recv_buf[2:self.ser.recv_len-1]
                    self.rcbuf.motor = self.ser.recv_buf[2]
                    self.rcbuf.sensor = self.ser.recv_buf[3]
                    #print(self.ser.recv_buf[4],self.ser.recv_buf[4]<<8,self.ser.recv_buf[5])

                    self.rcbuf.rotate = (int(self.ser.recv_buf[4]) +
                                         int(self.ser.recv_buf[5] << 8))
                    #print("struct:",self.rcbuf.motor,self.rcbuf.sensor,self.rcbuf.rotate)
                    #print(self.rcbuf)

                    self.rcflg = 1  #置接收成功标识

                self.ser.recv_len = 0  #清除进入循环条件
Esempio n. 12
0
 def programScannerChannel(self, channelNum, channel):  # list version
     self.__channelNum = channelNum
     self._channel = channel
     channelNumPadded = str("{0:0>3}".format(channelNum))
     inputTxt = []
     freqStr = str("{0:0>8}".format(round(channel.viewFreq())))
     #print(freqStr)
     inputTxt.append('PM' + str(channelNumPadded) + ' ' + freqStr)
     modeStr = channel.viewMode()
     inputTxt.append('RM' + ' ' + modeStr)
     serialportObj = SerialPort.SerialConnection()
     ser = serialportObj.open_connection()
     outTxt = serialportObj.serialIO(inputTxt, ser)
     #outTxt = connection.serialIO(inputTxt)
     return (outTxt)
Esempio n. 13
0
def main():
    # todo : 기본설정파일 로딩 (JSON 텍스트 파일 형식)
    makeJsonInit() # 설정 파일을 새로 만들 때 만 호출한다.
    dict_setting = json_loading("setting.json")

    print(dict_setting)

    # todo : 시리얼 통신 스레드를 연다.
    c_serial_port = SerialPort.SerialPort(dict_setting["SERIAL"]["PORT"], dict_setting["SERIAL"]["BAUD"], rcv_callback, send_thread)
    c_serial_port.threading()


    while (True):
        print("main sleep")
        time.sleep(1)
Esempio n. 14
0
    def __init__(self,
                 serial_port_id,
                 physical_device_id):
        """
        serial_port_id -> Give the serial port id as a variable name (i.e serial_port_2)
        Object can be addressed but serves as glue between SerialPort and Pin

        :param serial_port_id:
        :return:
        """
        super(Arduino, self).__init__(serial_port_id.serial_port,
                                      serial_port_id.baud_rate,
                                      serial_port_id.time_out,
                                      serial_port_id.serial_port_id)
        self.arduino_attr = SerialPort(self.serial_port,
                                       self.baud_rate,
                                       self.time_out,
                                       self.serial_port_id)
        self.physical_device_id = physical_device_id
Esempio n. 15
0
def freq_display():
    inputTxt = []
    inputTxt.append('MA')  # get frequency
    serialportObj = SerialPort.SerialConnection()
    ser = serialportObj.open_connection()
    outTxt = serialportObj.serialIO(inputTxt, ser)
    #channelTxt = 'Freq: ' + outTxt[6:10] + '.' + outTxt[10:14] + 'MHz'
    outTxtFreq = outTxt[6:13]
    channelTxt = ''.join([str(element) for element in outTxtFreq])
    outFreq = float(channelTxt) / 1000
    outFreq4dp = "{:.4f}".format(outFreq)
    display_message = 'Freq: ' + outFreq4dp + 'MHz'
    window = Tk()
    window.title("Frequency")
    window.geometry('350x200')
    txt = scrolledtext.ScrolledText(window, font='Verdana 11', width=40, height=10)
    txt.grid(column=0, row=0)
    txt.insert(INSERT, display_message)
    window.mainloop()
Esempio n. 16
0
 def __init__(self):
     self.serialPort = SerialPort()
Esempio n. 17
0
        print '[LOG] current frequency:', freq, 'Hz'

        sp.blinkSSVEP([freq, 0], 1, 1)

        time.sleep(time_length)

        sp.blinkSSVEP([0, 0], 1, 1)

        if freqs[freq] >= number_iterations:
            del freqs[freq]
            print '[LOG] removing frequency:', freq, 'Hz'

        print ''


sp = Sp.SerialPort('/dev/ttyUSB0')
sp.open()

sp.blinkSSVEP([0, 0], 1, 1)

print('Starting Task 1')

raw_input('Are you ready? ...')
task_1(sp)

raw_input('Are you ready? ...')
task_1(sp)

sp.close()
Esempio n. 18
0
 def __init__(self):
     self.serialPort = SerialPort()
Esempio n. 19
0
class CromeQD2:   

    def calcTempInCelsius(self,raw):
        raw = raw / 51.
        raw = (0.1423*pow(raw,6)) - (2.4938*pow(raw,5))  + (17.837*pow(raw,4)) - (68.698*pow(raw,3)) + (154.69*pow(raw,2)) - (232.75*raw) + 284.24
        return ((raw - 32.)*5.)/9.

    def __init__(self):
        self.serialPort = SerialPort()

    def getGear(self):
        gearRaw = self.serialPort.getByteFromThree(GEAR_B1_CROME14,GEAR_B2_CROME14,GEAR_B3_CROME14)
        return gearRaw

    def getRpm(self):
	try:
            rpmLowRaw=self.serialPort.getByte(RPMLOW_CROME14)
            rpmHighRaw=self.serialPort.getByte(RPMHIGH_CROME14) 
            return 1851562/((rpmHighRaw * 256) + rpmLowRaw)
	except: return 0
		
    def getBattery(self):
        batteryRaw = self.serialPort.getByte(BATT_CROME14)
        return (26.0 * batteryRaw) / 270.0

    def getIat(self):
        iatRaw = self.serialPort.getByte(IAT_CROME14)
        return self.calcTempInCelsius(iatRaw)

    def getEct(self):
        ectRaw = self.serialPort.getByte(ECT_CROME14)
	return self.calcTempInCelsius(ectRaw)

    def getTps(self):
        tpsRaw = self.serialPort.getByte(TPS_CROME14)
        tpsRaw = (0.4716  * tpsRaw) - 11.3184
        return tpsRaw

    def getO2(self):
        o2Raw = self.serialPort.getByte(O2_CROME14)
        return (2*o2Raw) + 10

    def getVss(self):
        vssRaw = self.serialPort.getByte(VSS_CROME14)
        return vssRaw

    def getMap(self):
        mapRaw = self.serialPort.getByte(MAP_CROME14)
        return (1764/255)*mapRaw

    def getInj(self):
        injLowRaw = self.serialPort.getByte(INJLOW_CROME14)
        injHighRaw = self.serialPort.getByte(INJHIGH_CROME14)
        injRaw = (injHighRaw * 256) + injLowRaw;
        return injRaw / 352

    def getIgn(self):
        ignRaw = self.serialPort.getByte(IGN_CROME14)
        return (0.25 * ignRaw) - 6

    def getDutyCycle(self):
        rpm = self.getRpm()
        inj = self.getInj()
        return (rpm * inj) / 1200

    def getVtec(self):
        vtec = self.serialPort.getByte(VTEC_CROME14)
        if (vtec == 67): return True
        else: return False
Esempio n. 20
0
##############################################################################
'''                                  IMPORT                                '''
##############################################################################
import config
import SerialPort
import WhatsappFuncs
##############################################################################
'''                                INISIASI                                '''
##############################################################################

##############################################################################
'''                                MAIN LOOP                               '''
##############################################################################

if __name__ == '__main__':
    config.init_config()
    SerialPort.init_serial()
    WhatsappFuncs.whatsapp_login()
    SerialPort.start_SMS_reader()
Esempio n. 21
0
def getRippleStatistics(tetrodes, analysis_time=4, show_ripples=False, \
        ripple_statistics=None, interrupt_ripples=False):
    """
    Get ripple data statistics for a particular tetrode and a user defined time
    period.
    Added: 2019/02/19
    Archit Gupta

    :tetrodes: Indices of tetrodes that should be used for collecting the
        statistics.
    :analysis_time: Amount of time (specified in seconds) for which the data
        should be analyzed to get ripple statistics.
    :show_ripple: Show ripple as they happen in real time.
    :ripple_statistics: Mean and STD for declaring something a sharp-wave
        ripple.
    :returns: Distribution of ripple power, ripple amplitude and frequency
    """

    if show_ripples:
        plt.ion()

    if interrupt_ripples:
        ser = SerialPort.BiphasicPort()
    n_tetrodes = len(tetrodes)
    report_ripples = (ripple_statistics is not None)

    # Create a ripple filter (discrete butterworth filter with cutoff
    # frequencies set at Ripple LO and HI cutoffs.)
    ripple_filter = signal.butter(RiD.LFP_FILTER_ORDER, \
            (RiD.RIPPLE_LO_FREQ, RiD.RIPPLE_HI_FREQ), \
            btype='bandpass', analog=False, output='sos', \
            fs=RiD.LFP_FREQUENCY)

    # Filter the contents of the signal frame by frame
    ripple_frame_filter = signal.sosfilt_zi(ripple_filter)

    # Tile it to take in all the tetrodes at once
    ripple_frame_filter = np.tile(np.reshape(ripple_frame_filter, \
            (RiD.LFP_FILTER_ORDER, 1, 2)), (1, n_tetrodes, 1))

    # Initialize a new client
    client = TrodesInterface.SGClient("RippleAnalyst")
    if (client.initialize() != 0):
        del client
        raise Exception("Could not initialize connection! Aborting.")

    # Access the LFP stream and create a buffer for trodes to fill LFP data into
    lfp_stream = client.subscribeLFPData(
        TrodesInterface.LFP_SUBSCRIPTION_ATTRIBUTE, tetrodes)
    lfp_stream.initialize()

    # LFP Sampling frequency TIMES desired analysis time period
    N_DATA_SAMPLES = int(analysis_time * RiD.LFP_FREQUENCY)

    # Each LFP frame (I think it is just a single time point) is returned in
    # lfp_frame_buffer. The entire timeseries is stored in raw_lfp_buffer.
    lfp_frame_buffer = lfp_stream.create_numpy_array()
    ripple_filtered_lfp = np.zeros((n_tetrodes, N_DATA_SAMPLES), dtype='float')
    raw_lfp_buffer = np.zeros((n_tetrodes, N_DATA_SAMPLES), dtype='float')
    ripple_power = np.zeros((n_tetrodes, N_DATA_SAMPLES), dtype='float')

    # Create a plot to look at the raw lfp data
    timestamps = np.linspace(0, analysis_time, N_DATA_SAMPLES)
    iter_idx = 0
    prev_ripple = -1.0
    prev_interrupt = -1.0

    # Data to be logged for later use
    ripple_events = []
    trodes_timestamps = []
    wall_ripple_times = []
    interrupt_events = []
    if report_ripples:
        print('Using pre-recorded ripple statistics')
        print('Mean: %.2f' % ripple_statistics[0])
        print('Std: %.2f' % ripple_statistics[1])

    if show_ripples:
        interruption_fig = plt.figure()
        interruption_axes = plt.axes()
        plt.plot([], [])
        plt.grid(True)
        plt.ion()
        plt.show()

    wait_for_user_input = input("Press Enter to start!")
    start_time = 0.0
    start_wall_time = time.perf_counter()
    interruption_iter = -1
    is_first_ripple = True
    while (iter_idx < N_DATA_SAMPLES):
        n_lfp_frames = lfp_stream.available(0)
        for frame_idx in range(n_lfp_frames):
            # print("t__%.2f"%(float(iter_idx)/float(RiD.LFP_FREQUENCY)))
            t_stamp = lfp_stream.getData()
            trodes_time_stamp = client.latestTrodesTimestamp()
            raw_lfp_buffer[:, iter_idx] = lfp_frame_buffer[:]

            # If we have enough data to fill in a new filter buffer, filter the
            # new data
            if (iter_idx > RiD.RIPPLE_SMOOTHING_WINDOW) and (
                    iter_idx % RiD.LFP_FILTER_ORDER == 0):
                lfp_frame = raw_lfp_buffer[:, iter_idx -
                                           RiD.LFP_FILTER_ORDER:iter_idx]
                # print(lfp_frame)
                filtered_frame, ripple_frame_filter = signal.sosfilt(ripple_filter, \
                       lfp_frame, axis=1, zi=ripple_frame_filter)
                # print(filtered_frame)
                ripple_filtered_lfp[:, iter_idx - RiD.
                                    LFP_FILTER_ORDER:iter_idx] = filtered_frame

                # Averaging over a longer window to be able to pick out ripples effectively.
                # TODO: Ripple power is only being reported for each frame
                # right now: Filling out the same value for the entire frame.
                frame_ripple_power = np.sqrt(np.mean(np.power( \
                        ripple_filtered_lfp[:,iter_idx-RiD.RIPPLE_SMOOTHING_WINDOW:iter_idx], 2), axis=1))
                ripple_power[:,iter_idx-RiD.LFP_FILTER_ORDER:iter_idx] = \
                        np.tile(np.reshape(frame_ripple_power, (n_tetrodes, 1)), (1, RiD.LFP_FILTER_ORDER))
                if report_ripples:
                    if is_first_ripple:
                        is_first_ripple = False
                    else:
                        # Show the previous interruption after a sufficient time has elapsed
                        if show_ripples:
                            if (iter_idx == int(
                                (prev_ripple + RiD.INTERRUPTION_WINDOW) *
                                    RiD.LFP_FREQUENCY)):
                                data_begin_idx = int(
                                    max(0,
                                        iter_idx - 2 * RiD.INTERRUPTION_TPTS))
                                interruption_axes.clear()
                                interruption_axes.plot(timestamps[data_begin_idx:iter_idx], raw_lfp_buffer[0, \
                                        data_begin_idx:iter_idx])
                                interruption_axes.scatter(prev_ripple,
                                                          0,
                                                          c="r")
                                interruption_axes.set_ylim(-3000, 3000)
                                plt.grid(True)
                                plt.draw()
                                plt.pause(0.001)
                                # print(raw_lfp_buffer[0, data_begin_idx:iter_idx])

                        # If any of the tetrodes has a ripple, let's call it a ripple for now
                        ripple_to_baseline_ratio = (frame_ripple_power[0] - ripple_statistics[0])/ \
                                ripple_statistics[1]
                        if (ripple_to_baseline_ratio >
                                RiD.RIPPLE_POWER_THRESHOLD):
                            current_time = float(iter_idx) / float(
                                RiD.LFP_FREQUENCY)
                            if ((current_time - prev_ripple) >
                                    RiD.RIPPLE_REFRACTORY_PERIOD):
                                prev_ripple = current_time
                                current_wall_time = time.perf_counter(
                                ) - start_wall_time
                                time_lag = (current_wall_time - current_time)
                                if interrupt_ripples:
                                    ser.sendBiphasicPulse()
                                print(
                                    "Ripple @ %.2f, Real Time %.2f [Lag: %.2f], strength: %.1f"
                                    % (current_time, current_wall_time,
                                       time_lag, ripple_to_baseline_ratio))
                                trodes_timestamps.append(trodes_time_stamp)
                                ripple_events.append(current_time)
                                wall_ripple_times.append(current_wall_time)

            iter_idx += 1
            if (iter_idx >= N_DATA_SAMPLES):
                break

    if client is not None:
        client.closeConnections()

    print("Collected raw LFP Data. Visualizing.")
    power_mean, power_std = Visualization.visualizeLFP(timestamps, raw_lfp_buffer, ripple_power, \
            ripple_filtered_lfp, ripple_events, do_animation=False)
    if report_ripples:
        writeLogFile(trodes_timestamps, ripple_events, wall_ripple_times,
                     interrupt_events)

    # Program exits with a segmentation fault! Can't help this.
    wait_for_user_input = input('Press ENTER to quit')
    return (power_mean, power_std)
 def initServer(self):
     self.UART = SerialPort(PORT, BAUDRATE)
     if self.UART.SUCCESS_OPEN:
         self.__serverSuccessFlag = True
     else:
         self.__serverSuccessFlag = False
Esempio n. 23
0
class CromeQD2:
    def calcTempInCelsius(self, raw):
        raw = raw / 51.0
        raw = (
            (0.1423 * pow(raw, 6))
            - (2.4938 * pow(raw, 5))
            + (17.837 * pow(raw, 4))
            - (68.698 * pow(raw, 3))
            + (154.69 * pow(raw, 2))
            - (232.75 * raw)
            + 284.24
        )
        return ((raw - 32.0) * 5.0) / 9.0

    def __init__(self):
        self.serialPort = SerialPort()

    def getGear(self):
        gearRaw = self.serialPort.getByteFromThree(GEAR_B1_CROME14, GEAR_B2_CROME14, GEAR_B3_CROME14)
        return gearRaw

    def getRpm(self):
        try:
            rpmLowRaw = self.serialPort.getByte(RPMLOW_CROME14)
            rpmHighRaw = self.serialPort.getByte(RPMHIGH_CROME14)
            return 1851562 / ((rpmHighRaw * 256) + rpmLowRaw)
        except:
            return 0

    def getBattery(self):
        batteryRaw = self.serialPort.getByte(BATT_CROME14)
        return (26.0 * batteryRaw) / 270.0

    def getIat(self):
        iatRaw = self.serialPort.getByte(IAT_CROME14)
        return self.calcTempInCelsius(iatRaw)

    def getEct(self):
        ectRaw = self.serialPort.getByte(ECT_CROME14)
        return self.calcTempInCelsius(ectRaw)

    def getTps(self):
        tpsRaw = self.serialPort.getByte(TPS_CROME14)
        tpsRaw = (0.4716 * tpsRaw) - 11.3184
        return tpsRaw

    def getO2(self):
        o2Raw = self.serialPort.getByte(O2_CROME14)
        return (2 * o2Raw) + 10

    def getVss(self):
        vssRaw = self.serialPort.getByte(VSS_CROME14)
        return vssRaw

    def getMap(self):
        mapRaw = self.serialPort.getByte(MAP_CROME14)
        return (1764 / 255) * mapRaw

    def getInj(self):
        injLowRaw = self.serialPort.getByte(INJLOW_CROME14)
        injHighRaw = self.serialPort.getByte(INJHIGH_CROME14)
        injRaw = (injHighRaw * 256) + injLowRaw
        return injRaw / 352

    def getIgn(self):
        ignRaw = self.serialPort.getByte(IGN_CROME14)
        return (0.25 * ignRaw) - 6

    def getDutyCycle(self):
        rpm = self.getRpm()
        inj = self.getInj()
        return (rpm * inj) / 1200

    def getVtec(self):
        vtec = self.serialPort.getByte(VTEC_CROME14)
        if vtec == 67:
            return True
        else:
            return False
Esempio n. 24
0
class Controller:
    def __init__(self):
        self.login = MainApp()
        self.cpuThread = QThread()
        self.scannerThread = QThread()
        self.open_admin = False
        self.open_user = False
        self.open_stats = False
        self.cpu = SerialPort('CPU')
        self.scanner = SerialPort('Scanner')
        self.cpu.moveToThread(self.cpuThread)
        self.scanner.moveToThread(self.scannerThread)

    def showLogin(self):
        if self.cpu.ComPort is None:
            self.cpu.portConnect()
        try:
            self.cpu.close()
        except Exception as e:
            print("Error Port :", e)

        if self.scanner.ComPort is None:
            self.scanner.portConnect()
        try:
            self.scanner.close()
        except Exception as e:
            print("Error Port:", e)

        self.login.QTxtLogin.setText('')
        self.login.QTxtPass.setText('')
        if not self.login.loaded:
            self.login.switchWindow.connect(self.showUser)
            self.login.loaded = True
        if self.open_admin:
            self.admin.close()
        if self.open_user:
            self.user.close()
        self.login.show()

    def showUser(self, text):
        try:
            self.cpuThread.started.disconnect()
            self.cpuThread.terminate()
            self.scannerThread.started.disconnect()
            self.scannerThread.terminate()
        except Exception as e:
            print(e)
        users = pd.read_csv(home_path[:-4] + '/files/users.csv')
        res = users[(users['username'] == text)]
        if res['username'].item() == "admin":
            if not self.open_admin:
                self.admin = Admin('')
                self.open_admin = True
            self.admin.login = text
            self.admin.handleHeaders()
            if not self.admin.loaded:
                self.admin.switchWindow.connect(self.showLogin)
                self.admin.switchWindow2.connect(self.showStats)
                self.admin.loaded = True
            if self.open_stats:
                self.stats.close()
            self.login.close()
            self.admin.show()
        else:
            if not self.open_user:
                self.user = User('')
                self.open_user = True
            self.user.QTxtRef.setText('')
            self.user.login = text
            self.user.handleHeaders()
            self.user.handleUI()
            if not self.user.loaded:
                self.user.switchWindow.connect(self.showLogin)
                self.user.switchWindow2.connect(self.showStats)
                self.user.sendsignal.connect(self.sendToOutput)
                self.user.loaded = True
            self.cpu.open()
            self.scanner.open()
            if not self.cpu.is_connected:
                self.cpu.signal.connect(self.user.recieveData)
                self.cpu.is_connected = True
            if not self.scanner.is_connected:
                self.scanner.signal.connect(self.user.recieveData)
                self.scanner.is_connected = True
            self.cpuThread.started.connect(self.cpu.readSerialPort)
            self.scannerThread.started.connect(self.scanner.readSerialPort)
            self.cpuThread.setTerminationEnabled(True)
            self.cpuThread.start()
            self.scannerThread.setTerminationEnabled(True)
            self.scannerThread.start()
            self.login.close()
            if self.open_stats:
                self.stats.close()
            self.user.show()

    def sendToOutput(self, data):
        print('[+]Sending', data, 'to serial port')
        self.cpu.writeSerialPort(data)

    def showScan(self, text):
        if not self.open_scan:
            self.scan = Scan('')
            self.open_scan = True
        self.scan.login = text.split(';')[0]
        self.scan.reference = text.split(';')[1]
        self.scan.quantity = int(text.split(';')[2])
        self.scan.processed = 0
        self.scan.handleHeaders()
        self.scan.handel_progressBar()
        if not self.scan.loaded:
            self.scan.switchWindow.connect(self.showUser)
            self.scan.loaded = True

        self.cpu.moveToThread(self.cpuThread)
        self.cpu.signal.connect(self.scan.recieveData)
        self.cpuThread.started.connect(self.cpu.readSerialPort)
        self.cpuThread.setTerminationEnabled(True)
        self.cpuThread.start()

        self.scanner.moveToThread(self.scannerThread)
        self.scanner.signal.connect(self.scan.recieveData)
        self.scannerThread.started.connect(self.scanner.readSerialPort)
        self.scannerThread.setTerminationEnabled(True)
        self.scannerThread.start()

        self.user.close()
        time.sleep(0.5)
        self.scan.show()

    def showStats(self, text):
        try:
            self.serialPort.close()
        except Exception as e:
            print("error PORT :", e)
        if not self.open_stats:
            self.stats = Statistics('')
            self.open_stats = True
        self.stats.login = text
        self.stats.handleHeaders()
        if not self.stats.loaded:
            self.stats.switchWindow.connect(self.showUser)
            self.stats.loaded = True
        self.stats.show()
        if self.open_admin:
            self.admin.close()
        if self.open_user:
            self.user.close()
Esempio n. 25
0
def scanner():
    global ChannelList
    global minChannel
    global maxChannel
    global inputValidation
    global connection

    inputValidation = {
        'channelRange': [minChannel, maxChannel],
        'freqRange': [[25, 512], [806, 956], [1240, 1300]],
        'validModes': ['AM', 'FM', 'NFM', 'WFM'],
        'validSteps': [5, 10, 12.5, 50, 100],
        'validDelay': [1, 4],
        'validChars': 16,
        'validPriorityLockout': ['Y', 'N']
    }

    minRange = str(inputValidation['channelRange'][0])
    maxRange = str(inputValidation['channelRange'][1])
    permissableFreqRanges = str(inputValidation['freqRange'])
    modeChoices = str(inputValidation['validModes'])
    stepChoices = str(inputValidation['validSteps'])
    delayChoices = str(inputValidation['validDelay'])
    maxChars = int(inputValidation['validChars'])
    validEntries = str(inputValidation['validPriorityLockout'])

    error = False
    ChannelList = [Channel(i) for i in range(maxChannel)]  # list comprehension
    # ChannelList = [Channel(i) for i in range(maxChannel - 1)]  # list comprehension
    # for i in range(maxChannel):
    #  ChannelList.append(Channel(i))

    menuChoices = """
Choose a menu item:
1: Create a new channel in internal memory
2: View channel in internal memory
3: Delete channel in internal memory
4: Write channels to csv
5: View all current channels in internal memory
6: Program scanner from csv file
7: View scanner channel
8: Write scanner channel
9: Read scanner bank(s)
10: Read all scanner channels
11. Open serial port
12. Close serial port
13. Scan
14. MAN (manual) key press
15: Exit        
    """

    quit = False
    while not quit:

        choice = inputCheck.inputException(menuChoices, 'integer', False, menuChoices, '', '')
        print('Menu choice is:', choice)

        if choice == 1:

            inputText = 'Enter the channel number to create. Range between: ' + minRange + ' and ' + maxRange
            channelNum = inputCheck.inputException(inputText, 'integer', False, '', 'channelRange', inputValidation)
            print('Channel is:', channelNum)

            inputText = 'Enter the frequency in MHz. Allowable ranges: ' + permissableFreqRanges
            freq = inputCheck.inputException(inputText, 'float', False, '', 'freqRange', inputValidation)
            print('Frequency is:', freq, 'MHz')

            inputText = 'Enter mode. Mode choices: ' + modeChoices
            mode = inputCheck.inputException(inputText, 'string', True, '', 'validModes', inputValidation)
            print('Mode is:', mode)

            inputText = 'Enter step. Step choices: ' + stepChoices
            step = inputCheck.inputException(inputText, 'float', False, '', 'validSteps', inputValidation)
            print('Step is:', step)

            inputText = 'Enter delay. Integer values between: ' + delayChoices
            delay = inputCheck.inputException(inputText, 'integer', False, '', 'validDelay', inputValidation)

            inputText = 'Enter alpha tag. Maximum characters: ' + str(maxChars)
            alphaTag = inputCheck.inputException(inputText, 'string', False, '', 'validChars', inputValidation)
            print('Alpha tag is:', alphaTag)

            inputText = 'Priority channel. Enter: ' + str(validEntries)
            priority = inputCheck.inputException(inputText, 'string', True, '', 'validPriorityLockout', inputValidation)

            inputText = 'Lockout channel? Enter:' + str(validEntries)
            lockout = inputCheck.inputException(inputText, 'string', True, '', 'validPriorityLockout', inputValidation)
            print('Lockout channel:', lockout)

            channel = Channel(channelNum, freq, mode, step, delay, alphaTag, priority, lockout)
            ChannelList.insert(channelNum - 1, channel)

        elif choice == 2:

            error = True
            while error:
                try:
                    channelNum = int(input('Enter channel number\n'))
                    error = False
                except ValueError:
                    print('Please enter an integer between', minChannel, 'and', maxChannel, '!\n')  # enhance to
                    # check between min & max channels
                else:
                    if channelNum < minChannel or channelNum > maxChannel:
                        print('Channel out of range')
                    else:
                        channel = ChannelList[channelNum - 1]
                        print('Properties of channel', channelNum)
                        print('Frequency: ', channel.viewFreq())
                        print('Mode: ', channel.viewMode())
                        print('Step: ', channel.viewStep())
                        print('Delay: ', channel.viewDelay())
                        print('Alpha tag: ', channel.viewAlphaTag())
                        print('Priority: ', channel.viewPriority())
                        print('Lockout: ', channel.viewLockout())

        elif choice == 3:
            channelNum = int(input('Enter channel number to delete\n'))
            channel = Channel(channelNum)
            ChannelList.insert(channelNum - 1, channel)

        elif choice == 4:
            write_csv(ChannelList)

        elif choice == 5:
            for i in range(maxChannel):
                print(i)
                channel = ChannelList[i]
                print(len(ChannelList))
                channelNum = i + 1
                print('Properties of channel', channelNum)
                print('Frequency: ', channel.viewFreq())
                print('Mode: ', channel.viewMode())
                print('Step: ', channel.viewStep())
                print('Delay: ', channel.viewDelay())
                print('Alpha tag: ', channel.viewAlphaTag())
                print('Priority: ', channel.viewPriority())
                print('Lockout: ', channel.viewLockout())

        elif choice == 6:
            read_csv_program_scanner()

        elif choice == 7:
            channelNum = str(input('Enter scanner channel number\n'))
            scannerChannel = serialCommand(channelNum)
            print('Scanner data for channel', channelNum, 'is:', scannerChannel.viewScannerChannel(channelNum))

        elif choice == 8:
            inputText = 'Enter the channel number to create. Range between: ' + minRange + ' and ' + maxRange
            channelNum = inputCheck.inputException(inputText, 'integer', False, '', 'channelRange', inputValidation)

            inputText = 'Enter the frequency in MHz. Allowable ranges: ' + permissableFreqRanges
            freq = inputCheck.inputException(inputText, 'float', True, '', 'freqRange', inputValidation) * 10000  #
            # eg format to use to speak to communicate with scanner: 243MHz = 2430000

            inputText = 'Enter mode. Mode choices: ' + modeChoices
            mode = inputCheck.inputException(inputText, 'string', True, '', 'validModes', inputValidation)

            inputText = 'Enter step. Step choices: ' + stepChoices
            step = inputCheck.inputException(inputText, 'float', False, '', 'validSteps', inputValidation)

            inputText = 'Enter delay. Integer values between: ' + delayChoices
            delay = inputCheck.inputException(inputText, 'integer', False, '', 'validDelay', inputValidation)

            inputText = 'Enter alpha tag. Maximum characters: ' + str(maxChars)
            alphaTag = inputCheck.inputException(inputText, 'string', False, '', 'validChars', inputValidation)

            inputText = 'Priority channel. Enter: ' + str(validEntries)
            priority = inputCheck.inputException(inputText, 'string', True, '', 'validPriorityLockout', inputValidation)

            inputText = 'Lockoutchannel? Enter: ' + str(validEntries)
            lockout = inputCheck.inputException(inputText, 'string', True, '', 'validPriorityLockout', inputValidation)

            channel = Channel(channelNum, freq, mode, step, delay, alphaTag, priority, lockout)
            scannerChannel = serialCommand(channelNum)
            print(scannerChannel.programScannerChannel(channelNum, channel))

        elif choice == 9:
            bankNum = int(input('Enter a bank number to read'))
            readBank(bankNum)

        elif choice == 10:
            readAll(maxChannel)

        elif choice == 11:  # add exception handling for integer port numbers & permissable baud rates: 2400, 4800,
            # 9600, 19200...
            port = int(input('Enter COM port to connect to scanner'))
            portStr = 'COM' + str(port)
            baudrate = int(input('Enter baudrate'))
            connection = SerialPort.SerialConnection()
            print(connection.open_connection(portStr, baudrate, 1))

        elif choice == 12:
            try:
                print(connection.close_connection())
            except AttributeError:  # COM port has not been opened yet...
                print('COM port has not been opened yet.')

        elif choice == 13:
            scan = '1'
            dummy_channel = serialCommand(scan)
            # scanner_mode = dummy_channel.checkMode()  # no need to check scanner mode of operation...
            # if scanner_mode == '00':
            #     scanner_mode = dummy_channel.manualMode()
            #     print('Manual mode')
            # else:
            #     scanner_mode = dummy_channel.scanMode()
            #     print('Scan mode')
            dummy_channel.scanMode()

        elif choice == 14:
            scan = '1'
            dummy_channel = serialCommand(scan)
            # scanner_mode = dummy_channel.checkMode()  # no need to check scanner mode of operation...
            # if scanner_mode == '00':
            #     scanner_mode = dummy_channel.manualMode()
            #     print('Manual mode')
            # else:
            #     scanner_mode = dummy_channel.scanMode()
            #     print('Scan mode')
            dummy_channel.manualMode()

        elif choice == 15:
            quit = True

        else:
            print('Invalid menu choice')
Esempio n. 26
0
#! /usr/bin/env python3


import SerialPort

if __name__ == '__main__':

    serial_port = SerialPort.SerialPort()
    serial_port.open()
    serial_port.transmit_binary([0x03])
#    serial_port.send_help()
    serial_port.close()
class WindowUtama(QMainWindow):
    def __init__(self):
        super().__init__()

        self.__serverSuccessFlag = False
        self.__firstmessagefound = False
        self.__printfirstmessage = False
        self.pause = False
        self.count = 0
        self.x_data = np.arange(DATA_LENGTH)
        self.freqs = FFTmodule.fftfreq(DATA_LENGTH,
                                       SAMPLE_INTERVAL)[:DATA_LENGTH // 2]
        self.magnitude = [0] * len(self.freqs)
        self.y_data = [0] * np.size(self.x_data)

        self.initServer()

        if self.__serverSuccessFlag:
            print(f"Server at {PORT}, {BAUDRATE} bps")
            self.initUi()
            self.resize(1000, 700)
            self.show()
            self.setTimer()
        else:
            exit(1)

    def initServer(self):
        self.UART = SerialPort(PORT, BAUDRATE)
        if self.UART.SUCCESS_OPEN:
            self.__serverSuccessFlag = True
        else:
            self.__serverSuccessFlag = False

    def initUi(self):
        self.setWindowTitle("Elektro - (Serial) Data Pysualization")

        # config main widget
        self.MainWidget = QWidget()
        self.MainWidgetLayout = QGridLayout()
        self.MainWidget.setLayout(self.MainWidgetLayout)

        # place the main widget in main window
        self.setCentralWidget(self.MainWidget)

        # INIT PLOTS -------------------------------------------------
        self.List_of_Plots = []
        self.TimePlot = FigureWidget(title=f"Time Domain",
                                     color=20,
                                     yRange=Y_LIMIT)
        self.FreqPlot = FigureWidget(title=f"Frequency Domain",
                                     color=40,
                                     yRange=[-20, 120])
        self.List_of_Plots.append(self.TimePlot)
        self.List_of_Plots.append(self.FreqPlot)

        # INIT CHANNEL INFO ------------------------------------------
        self.List_of_channels = []
        #for n in range(2):
        #    self.channel_n = ChannelWidget(title="Channel", num=n+1)
        #    self.List_of_channels.append(self.channel_n)

        # ADD WIDGETS TO LAYOUT --------------------------------------
        self.MainWidgetLayout.addWidget(self.List_of_Plots[0], 0, 0)
        self.MainWidgetLayout.addWidget(self.List_of_Plots[1], 1, 0)

        #self.MainWidgetLayout.addWidget(self.List_of_channels[0], 0, 2)
        #self.MainWidgetLayout.addWidget(self.List_of_channels[1], 1, 2)

    def setTimer(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.updateAll)
        self.timer.start(0)

    def updateAll(self):
        #self.start_time = time.time()

        try:
            data = self.UART.getNewData()
            if data.find(FIRST_MESSAGE):
                self.__firstmessagefound = True
                if not self.__printfirstmessage:
                    print("Found first message!")
                    self.__printfirstmessage = True

            if self.__firstmessagefound:
                data = float(data) * 5 / 1024
                self.y_data.append(data)
                self.y_data.pop(0)

                self.magnitude = FFTmodule.fft(self.y_data)
                self.magnitude = 20 * np.log(
                    np.abs(self.magnitude[:DATA_LENGTH // 2]))

                if not self.pause:
                    self.List_of_Plots[0].PlotData(self.x_data, self.y_data)
                    self.List_of_Plots[1].PlotData(self.freqs, self.magnitude)

                else:
                    print("Paused!")

        except KeyboardInterrupt:
            print("\nKeyboard Interrupted!")
            try:
                self.UART.close()
            except:
                print("Serial port already closed")
            exit(1)

        except ValueError:
            pass