Esempio n. 1
0
def execute_action(action_type, action_message, action_address=None):
    action_dic = {'type': str(action_type.name)}
    if action_type in [ActionType.relay_A, ActionType.relay_B]:
        action = 'set' if action_message else 'clear'
        logger.debug('action:' + str(action_type) + ' ' + action)
        action_dic['action'] = action
    if action_type == ActionType.send_SMS:
        action_dic['phone_number'] = action_address
        action_dic['text'] = action_message
    actions_str = json.dumps({'actions': [action_dic]})
    try:
        with open('/var/lib/cloud9/ndas_rt/fifos/trigger', 'w') as p:
            p.write(actions_str + '\n')
        logger.info("Trigger fired!")
    except Exception as ex:
        logger.error("Error writing data to trigger pipe:" + str(ex))
    return actions_str
Esempio n. 2
0
def signal_receiver(host, port):

    st = Stream()
    skip_packet = True
    delta_ns = 10**9
    limit_ns = 5 * delta_ns

    chs_ref = []

    params_dic = None

    #trigger_wrapper = TriggerWrapper(context, 1, TriggerType.sta_lta, 1000, True, 100, 300, 3, 1, 1, 4)
    while True:
        try:
            socket_raw = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_address = (host, port)
            socket_raw.connect(server_address)
            socket_wrapper = SocketWrapper(socket_raw)
            header = socket_wrapper.recv(6)
            if header != b'NJSP\0\0':
                mes = f'incorrect header:{header}'
                logger.error(mes)
                raise Exception(mes)
            logger.info('header received')
            while True:
                size_bytes = socket_wrapper.recv(8)
                if len(size_bytes) != 8:
                    logger.error(
                        f'incorrect len: {len(size_bytes)}, expected:8')
                size = int(size_bytes.decode(), 16)
                if not 20 < size < 50000:
                    logger.warning('possibly incorrect data size:' + str(size))
                    continue
                raw_data = socket_wrapper.recv(size)
                if len(raw_data) != size:
                    logger.error(
                        f'incorrect len: {len(raw_data)}, expected:{size}')
                if not raw_data[:1] == b'{':
                    logger.error('no start \'{\' symbol')
                    continue
                if raw_data[-1:] != b'}':
                    logger.error('incorrect last symbol, \'}\' expected')
                    continue
                try:
                    json_data = json.loads(raw_data.decode('utf-8'),
                                           object_pairs_hook=OrderedDict)
                except Exception as e:
                    logger.error('cannot parse json data:\n' + str(raw_data) +
                                 '\n' + str(e))
                    continue
                if 'parameters' in json_data:
                    logger.debug('received parameters')
                    streams_dic = json_data['parameters']['streams']
                    STREAM_NAME = list(streams_dic.keys())[STREAM_IND]
                    params_dic = streams_dic[STREAM_NAME]
                    #print('params bytes sent to inner socket:' + str(Subscription.parameters.value + size_bytes + raw_data))
                if 'streams' in json_data:
                    #sampling_rate = json_data['streams']['sample_rate']
                    starttime = UTCDateTime(
                        json_data['streams'][STREAM_NAME]['timestamp'])
                    logger.debug('received packet, dt:' + str(starttime))
                    chs = json_data['streams'][STREAM_NAME]['samples']
                    if not chs_ref:
                        chs_ref = sorted(chs)
                        #units = json_data['signal']['counts']
                    sample_rate = params_dic['sample_rate']

        except Exception as ex:
            logger.error(f'exception:{ex}')
        finally:
            socket_raw.close()
Esempio n. 3
0
import time
import zmq

from obspy import UTCDateTime

from detector.filter_trigger.StaLtaTrigger import logger
from detector.send_receive.tcp_client import TcpClient

context = zmq.Context()
client = TcpClient('tcp://192.168.0.189:5555', context)

while True:
    data = client.recv(13)
    logger.debug('received:' + str(data))

Esempio n. 4
0
def action_process(action_id,
                   send_func,
                   rules=[],
                   args={},
                   pet=0,
                   infinite=False):
    #logger.debug('start process for action ' + str(action_id))
    context = zmq.Context()
    socket_sub = context.socket(zmq.SUB)
    socket_sub.connect('tcp://localhost:' + str(Port.proxy.value))
    action_id_s = '%02d' % action_id
    socket_sub.setsockopt(zmq.SUBSCRIBE,
                          Subscription.test.value + action_id_s.encode())
    if action_id in [1, 2]:
        args['relay_n'] = action_id
        args['on_off'] = 0
        send_func(**args)  # initialization
        #logger.debug('use test subscription:' + str(Subscription.test.value + action_id_s.encode()))
    for rule_id in rules:
        rule_id_s = '%02d' % rule_id
        socket_sub.setsockopt(zmq.SUBSCRIBE,
                              Subscription.rule.value + rule_id_s.encode())
    trigger = 0
    wait_pet = False
    infinite_on = False
    while True:
        # if action_id in [1, 2]:
        #     logger.debug('wait event')
        if socket_sub.poll(max(pet, 1) *
                           1000):  # if pet=0 wait one second second
            logger.debug('trigger:' + str(trigger))
            bin_message = socket_sub.recv()
            if bin_message[:1] == Subscription.test.value:
                if infinite:
                    infinite_on = False
                    trigger = 0
                if trigger == 0:
                    if action_id in [1, 2]:
                        logger.debug('test event')
                    args['on_off'] = 1
                    send_func(**args)
                    wait_pet = True
                    # sleep(max(pet, 1))
                    # args['on_off'] = 0
                    # send_func(**args)
            elif not infinite_on:
                if int(bin_message[3:4]):
                    trigger_val = 1
                    if infinite:
                        infinite_on = True
                else:
                    trigger_val = -1
                # if action_id in [1, 2]:
                #     if trigger_val > 0:
                #         logger.debug('trigger event')
                #     else:
                #         logger.debug('detrigger event')
                trigger += trigger_val
                if trigger == 1 and trigger_val == 1:
                    args['on_off'] = 1
                    send_func(**args)
                if trigger == 0:
                    if pet:
                        wait_pet = True
                    else:
                        args['on_off'] = 0
                        send_func(**args)
                if trigger < 0:
                    if action_id in [1, 2]:
                        logger.warning('unexpected detriggering')
                    trigger = 0
        else:
            # if action_id in [1, 2]:
            #     logger.debug('no event, pet:' + str(pet))
            if trigger == 0 and wait_pet and not infinite_on:
                wait_pet = False
                args['on_off'] = 0
                send_func(**args)
Esempio n. 5
0
def signal_receiver(conn_str, station_bin, triggers_params):
    station = station_bin.decode()
    show_signal = False  # os.name == 'nt'
    if station != 'ND02':
        show_signal = False

    context = zmq.Context()
    #socket = NjspClient(conn_str, context)
    str_parts = conn_str.split(':')[-2:]
    host = str_parts[0][2:]
    port = str_parts[-1]
    stream_reader = NJSP_STREAMREADER((host, int(port)))
    stream_reader.connected_event.wait()
    init_packet = stream_reader.init_packet.copy()
    STREAM_NAME = list(init_packet['parameters']['streams'].keys())[0]

    socket_pub = context.socket(zmq.PUB)
    conn_str_pub = 'tcp://localhost:' + str(Port.multi.value)
    socket_pub.connect(conn_str_pub)
    socket_buf = context.socket(zmq.PUB)
    socket_buf.connect(conn_str_pub)

    #show_signal = station == 'ND02'
    if station != STREAM_NAME:
        init_packet['parameters']['streams'][station] = \
                init_packet['parameters']['streams'][STREAM_NAME]
        del init_packet['parameters']['streams'][STREAM_NAME]
    params_dic = init_packet['parameters']['streams'][station]

    socket_confirm = context.socket(zmq.SUB)
    socket_confirm.connect('tcp://localhost:' + str(Port.proxy.value))
    socket_confirm.setsockopt(zmq.SUBSCRIBE, Subscription.confirm.value)

    confirmed = None

    trigger_objs_dic = None

    if show_signal:
        from matplotlib import pyplot
        from obspy import Stream, Trace
        pyplot.ion()
        figure = pyplot.figure()
        st = Stream()
    check_time = None
    times_dic = OrderedDict()
    skip_packet = True
    delta_ns = 10**9
    limit_ns = 5 * delta_ns

    chs_ref = []

    #trigger_wrapper = TriggerWrapper(context, 1, TriggerType.sta_lta, 1000, True, 100, 300, 3, 1, 1, 4)
    while True:
        if not stream_reader.connected_event.is_set():
            logger.warning('kill stream_reader')
            stream_reader.kill()
            stream_reader = NJSP_STREAMREADER((host, port))
            logger.warning('wait connection...')
            if not stream_reader.connected_event.wait():
                continue
            logger.info('stream_reader connected')
            init_packet = stream_reader.init_packet.copy()
            if station != STREAM_NAME:
                init_packet['parameters']['streams'][station] = \
                    init_packet['parameters']['streams'][STREAM_NAME]
                del init_packet['parameters']['streams'][STREAM_NAME]
            socket_buf.send(Subscription.parameters.value +
                            json.dumps(init_packet).encode())
            params_dic = init_packet['parameters']['streams'][station]
            if confirmed:
                socket_buf.send(Subscription.parameters.value +
                                json.dumps(init_packet).encode())
        #logger.debug('wait data packet')
        try:
            packet = stream_reader.queue.get(timeout=0.5)
        except:
            packet = None
        # if packet:
        #     logger.debug('packet received')
        if not packet or 'streams' not in packet:
            continue
        if not confirmed:
            logger.debug('wait confirmation')
            socket_confirm.recv()
            logger.debug('signal resent confirmed')
            confirmed = True
            socket_buf.send(Subscription.parameters.value +
                            json.dumps(init_packet).encode())
        starttime = UTCDateTime(packet['streams'][STREAM_NAME]['timestamp'])
        #logger.debug('received packet, dt:' + str(starttime))
        if skip_packet:
            times_dic[UTCDateTime()._ns] = starttime._ns
            while len(times_dic.keys()) > 2 and \
                        list(times_dic.keys())[-2] - list(times_dic.keys())[0] > limit_ns:
                del times_dic[list(times_dic.keys())[0]]
            if list(times_dic.keys())[-1] - list(times_dic.keys())[0] > limit_ns and \
                    limit_ns - delta_ns < list(times_dic.values())[-1] - list(times_dic.values())[0] < \
                        limit_ns + 2 * delta_ns:
                skip_packet = False
            else:
                logger.info('skip packet')
                continue
        chs = packet['streams'][STREAM_NAME]['samples']
        if not chs_ref:
            chs_ref = sorted(chs)
            #units = json_data['signal']['counts']
            set_source_channels(station, chs_ref)
        sample_rate = params_dic['sample_rate']
        if trigger_objs_dic is None:
            trigger_objs_dic = {}
            for ch, trigger_params_list in triggers_params.items():
                if ch not in trigger_objs_dic:
                    trigger_objs_dic[ch] = []
                for trigger_params in trigger_params_list:
                    trigger_params['sampling_rate'] = int(sample_rate)
                    trigger_params['context'] = context
                    trigger_objs_dic[ch].append(
                        TriggerWrapper(**trigger_params))
        for ch in chs:
            bin_header = ChHeader(station_bin, ch, int(sample_rate),
                                  starttime._ns)
            bin_signal_int = packet['streams'][STREAM_NAME]['samples'][ch]
            k = params_dic['channels'][ch]['counts_in_volt']
            data = np.frombuffer(bin_signal_int,
                                 dtype='int32').astype('float') / k
            if ch in trigger_objs_dic:
                for trigger_obj in trigger_objs_dic[ch]:
                    trigger_obj.pick(starttime, data)

            if show_signal:
                tr = Trace()
                tr.stats.starttime = starttime
                tr.stats.sampling_rate = sample_rate
                tr.stats.channel = ch
                tr.data = data
                st += tr

        custom_header = CustomHeader()
        chs_blist = list(map(prep_ch, chs))
        chs_bin = b''.join(chs_blist)
        custom_header.channels = cast(chs_bin, POINTER(ChName * 20)).contents
        custom_header.ns = starttime._ns
        data_dic = packet['streams'][STREAM_NAME]['samples']
        for ch in data_dic:
            ch_data = data_dic[ch]
            data_dic[ch] = base64.encodebytes(ch_data).decode()
        if station != STREAM_NAME:
            packet['streams'][station] = packet['streams'][STREAM_NAME]
            del packet['streams'][STREAM_NAME]
        socket_buf.send(Subscription.signal.value + custom_header +
                        json.dumps(packet).encode())

        if not check_time:
            check_time = starttime
        if show_signal and starttime > check_time + 1:
            check_time = starttime
            st.sort().merge()
            st.trim(starttime=st[0].stats.endtime - 10)
            pyplot.clf()
            st.plot(fig=figure)
            pyplot.show()
            pyplot.pause(.1)