async def manage_client(self, event_manger, client, msg_size, rabbit_channel):
        """
            It receives modbus data from iiot gateway using client socket.
            event_manger        It has asyncio event loop
            client              It is a client socket that works with multiple iiot gateways.
            msg_size            It means the packet size to be acquired at a time from the client socket.
            msg_queue           It means the queue containing the message transmitted from the gateway.
        """

        fac_daq = get_fac_inf(self.redis_mgr)
        with GracefulInterruptHandler() as h:
            while True:
                if not h.interrupted:
                    try:
                        packet = (await event_manger.sock_recv(client, msg_size))
                    except Exception as e:
                        client.close()
                        logging.debug('Client socket close by exception:' + str(e.args))
                        h.release()
                        break
                    if packet:
                        try:
                            logging.debug('try convert')
                            host, port = client.getpeername()
                            status, packet, modbus_udp = self.convert_hex2decimal(packet, host, port)
                            if status == 'OK':
                                equipment_id = modbus_udp['equipment_id']
                                logging.debug('equipment_id:' + equipment_id)
                                redis_fac_info = json.loads(self.redis_mgr.get('facilities_info'))
                                if equipment_id in redis_fac_info.keys():
                                    logging.debug('config factory message')
                                    fac_msg = config_fac_msg(equipment_id, fac_daq, modbus_udp, redis_fac_info)
                                    
                                    rabbit_channel, rtn_json = self.publish_facility_msg(mqtt_con=rabbit_channel,
                                                                                         exchange_name='facility',
                                                                                         routing_key=equipment_id,
                                                                                         json_body=fac_msg)
                                    if rtn_json == json.loads(fac_msg):
                                        logging.debug(
                                            'mq body:' + str(json.dumps({equipment_id: fac_daq[equipment_id]})))
                                    else:
                                        logging.exception("MQTT Publish Excetion:" + str(rtn_json))
                                        raise NameError('MQTT Publish exception')
                                
                                else:
                                    acq_message = status + packet + 'is not exist equipment_id key\r\n'
                                    logging.debug(acq_message)
                                    client.sendall(acq_message.encode())
                                    continue
                            acq_message = status + packet + '\r\n'
                            logging.debug('rtn:' + acq_message)
                            client.sendall(acq_message.encode())
                        except Exception as e:
                            client.sendall(packet.encode())
                            logging.exception('message error:' + str(e))
                    else:
                        client.close()
                else:
                    client.close()
                    sys.exit(0)
 async def get_client(self, event_manger, server_sock, msg_size, rabbit_channel):
     """
     It create client socket with server sockt
     event_manger        It has asyncio event loop
     server_socket       Socket corresponding to the client socket
     msg_size            It means the packet size to be acquired at a time from the client socket.
     msg_queue           It means the queue containing the message transmitted from the gateway.
     """
     with GracefulInterruptHandler() as h:
         client = None
         while True:
             if not h.interrupted:
                 client, _ = await event_manger.sock_accept(server_sock)
                 event_manger.create_task(self.manage_client(event_manger, client, msg_size, rabbit_channel))
             else:
                 client.close()
                 server_sock.close()
                 sys.exit(0)
Exemplo n.º 3
0
 async def manage_client(self, event_manger, client, msg_size, redis_con,
                         mq_channel):
     """
         It receives modbus data from iiot gateway using client socket.
         event_manger        It has asyncio event loop
         client              It is a client socket that works with multiple iiot gateways.
         msg_size            It means the packet size to be acquired at a time from the client socket.
         msg_queue           It means the queue containing the message transmitted from the gateway.
     """
     facilities_dict = {}
     facilities_info = json.loads(redis_con.get('facilities_info').decode())
     equipment_keys = facilities_info.keys()
     for equipment_key in equipment_keys:
         facilities_dict[equipment_key] = {}
         for sensor_id in facilities_info[equipment_key].keys():
             sensor_desc = facilities_info[equipment_key][sensor_id]
             if sensor_desc not in facilities_dict[equipment_key].keys():
                 facilities_dict[equipment_key][sensor_desc] = 0.0
     with GracefulInterruptHandler() as h:
         while True:
             if not h.interrupted:
                 try:
                     packet = (await
                               event_manger.sock_recv(client, msg_size))
                     if packet:
                         try:
                             logging.debug('try convert')
                             status, packet, modbus_udp = self.convert_hex2decimal(
                                 packet, client)
                             if status == 'OK':
                                 str_modbus_udp = str(modbus_udp)
                                 logging.debug('Queue put:' +
                                               str_modbus_udp)
                                 equipment_id = modbus_udp['equipment_id']
                                 sensor_code = modbus_udp['meta'][
                                     'sensor_cd']
                                 redis_sensor_info = json.loads(
                                     redis_con.get('facilities_info'))
                                 if equipment_id in redis_sensor_info.keys(
                                 ):
                                     sensor_desc = redis_sensor_info[
                                         equipment_id][sensor_code]
                                     routing_key = modbus_udp[
                                         'equipment_id']
                                     facilities_dict[equipment_key][
                                         'time'] = modbus_udp['meta'][
                                             'time']
                                     facilities_dict[equipment_key][
                                         sensor_desc] = modbus_udp['meta'][
                                             'sensor_value']
                                     logging.debug(routing_key + ',' +
                                                   sensor_desc + ', update')
                                     logging.debug(str(facilities_dict))
                                     mq_channel.basic_publish(
                                         exchange='facility',
                                         routing_key=routing_key,
                                         body=json.dumps(facilities_dict))
                                 else:
                                     acq_message = status + packet + 'no exist key\r\n'
                                     client.sendall(acq_message.encode())
                                     continue
                             acq_message = status + packet + '\r\n'
                             client.sendall(acq_message.encode())
                         except Exception as e:
                             client.sendall(packet.encode())
                             logging.exception('message error:' + str(e))
                     else:
                         client.close()
                 except Exception as e:
                     logging.exception('manage client exception:' + str(e))
                     break
             else:
                 client.close()
                 sys.exit(0)
Exemplo n.º 4
0
    async def manage_client(self, event_manger, client, msg_size, mq_channel):
        """
            It receives modbus data from iiot gateway using client socket.
            event_manger        It has asyncio event loop
            client              It is a client socket that works with multiple iiot gateways.
            msg_size            It means the packet size to be acquired at a time from the client socket.
            msg_queue           It means the queue containing the message transmitted from the gateway.
        """
        facilities_dict = {}
        facilities_info = json.loads(
            self.redis_con.get('facilities_info').decode())
        equipment_keys = facilities_info.keys()
        for equipment_key in equipment_keys:
            facilities_dict[equipment_key] = {}
            for sensor_id in facilities_info[equipment_key].keys():
                sensor_desc = facilities_info[equipment_key][sensor_id]
                if sensor_desc not in facilities_dict[equipment_key].keys():
                    facilities_dict[equipment_key][sensor_desc] = 0.0

        with GracefulInterruptHandler() as h:
            while True:
                if not h.interrupted:
                    try:
                        packet = (await
                                  event_manger.sock_recv(client, msg_size))
                    except Exception as e:
                        logging.exception('manage client exception:' + str(e))
                        client.close()
                        break

                    if packet:
                        try:
                            logging.debug('try convert')
                            host, port = client.getpeername()
                            status, packet, modbus_udp = self.convert_hex2decimal(
                                packet, host, port)
                            if status == 'OK':
                                str_modbus_udp = str(modbus_udp)
                                logging.debug('Queue put:' + str_modbus_udp)
                                equipment_id = modbus_udp['equipment_id']
                                sensor_code = modbus_udp['meta']['sensor_cd']

                                redis_sensor_info = json.loads(
                                    self.redis_con.get('facilities_info'))
                                if equipment_id in redis_sensor_info.keys():
                                    sensor_desc = redis_sensor_info[
                                        equipment_id][sensor_code]
                                    routing_key = modbus_udp['equipment_id']
                                    facilities_dict[equipment_key][
                                        'time'] = modbus_udp['meta']['time']
                                    pv = modbus_udp['meta']['sensor_value']
                                    decimal_point = modbus_udp['meta'][
                                        'decimal_point']
                                    pv = float(
                                        pv
                                    )  #* math.pow(10, float(decimal_point))
                                    decimal_point = math.pow(
                                        10, float(decimal_point))
                                    modbus_udp['meta'][
                                        'sensor_value'] = pv / decimal_point
                                    logging.debug('redis:' + 'gateway_cvt set')
                                    self.redis_con.set('remote_log:modbus_udp',
                                                       json.dumps(modbus_udp))

                                    facilities_dict[equipment_key][
                                        sensor_desc] = modbus_udp['meta'][
                                            'sensor_value']
                                    logging.debug('mq exchange:facility')
                                    logging.debug('mq routing_key:' +
                                                  routing_key)
                                    logging.debug(
                                        'mq body:' +
                                        str(json.dumps(facilities_dict)))
                                    try:
                                        logging.debug('mqtt open')
                                        mq_channel.basic_publish(
                                            exchange='facility',
                                            routing_key=routing_key,
                                            body=json.dumps(facilities_dict))

                                        self.redis_con.set(
                                            'remote_log:mqttpubish',
                                            json.dumps(facilities_dict))
                                    except Exception as e:
                                        logging.debug('mqtt closed')
                                else:
                                    acq_message = status + packet + 'no exist key\r\n'
                                    client.sendall(acq_message.encode())
                                    continue
                            acq_message = status + packet + '\r\n'
                            logging.debug('rtn:' + acq_message)
                            client.sendall(acq_message.encode())
                        except Exception as e:
                            client.sendall(packet.encode())
                            logging.exception('message error:' + str(e))
                    else:
                        client.close()
                else:
                    client.close()
                    sys.exit(0)