ninjablock_bridge.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 #
00003 # License: BSD
00004 #   https://raw.github.com/robotics-in-concert/rocon_devices/license/LICENSE
00005 #
00006 #################################################################################
00007 
00008 import json
00009 import requests
00010 import rospy
00011 import rocon_std_msgs.msg as rocon_std_msgs
00012 import rocon_device_msgs.msg as rocon_device_msgs
00013 from rocon_iot_bridge import RoconIOTBridge, Connector
00014 
00015 
00016 class NinjaBlockConnector(Connector):
00017 
00018     _API = {
00019         'UPDATE_CONFIG': 'configuration',
00020         'GET_DEVICE_LIST': 'get_device_list',
00021         'LOG':  'log',
00022         'RESET': 'reset'
00023     }
00024 
00025     def __init__(self):
00026         self._configuration_file = rospy.get_param('~target_configuration_file')
00027         self._devices_msgs = []
00028         self.type_table = {}
00029 
00030     def _load_configuration(self, filename):
00031         with open(filename) as f:
00032             config = json.load(f)
00033         self._config = config
00034 
00035         if not 'access_token' in self._config:
00036             return False
00037         else:
00038             return True
00039 
00040     def init(self, config=None):
00041 
00042         if not self._load_configuration(self._configuration_file):
00043             return None, "Error while loading configuration : %s" % self._config
00044 
00045         self._endpoint_url = self._get_endpoint_url()
00046 
00047         if config:
00048             return self.request_configuration_update(config)
00049         else:
00050             return None, "No configuration is given"
00051 
00052     def close(self):
00053         return self._request_reset()
00054 
00055     def call_get_device_list(self):
00056         return self._get_device_list()
00057 
00058     def _type_converter(self, device_label):
00059         label = device_label.replace(' ', '_').lower()
00060         type_table = self._config['type_table']
00061         return_type = "none"
00062         for tp in type_table.keys():
00063             if return_type == "none":
00064                 for device_type in type_table[tp]:
00065                     if device_type in label:
00066                         return_type = tp
00067                         break
00068         return return_type
00069 
00070     def _convert_to_device_msgs(self, device_raw_data):
00071         msgs = []
00072         for dev_id in device_raw_data:
00073             device = device_raw_data[dev_id]
00074             if device['has_subdevice_count'] is 1:
00075                 for sdev_id in device['subDevices']:
00076                     sub_device = device['subDevices'][sdev_id]
00077                     dev = rocon_device_msgs.Device()
00078                     dev.label = sub_device['shortName']
00079                     dev.type = self._type_converter(dev.label)
00080                     dev.uuid = str(dev_id) + '_' + str(sub_device['data'])
00081                     dev.data.append(rocon_std_msgs.KeyValue('guid', str(dev_id)))
00082                     dev.data.append(rocon_std_msgs.KeyValue('data', ''))
00083                     msgs.append(dev)
00084             else:
00085                 dev = rocon_device_msgs.Device()
00086                 dev.label = device['shortName'].replace(' ', '_').lower()
00087                 dev.type = device['device_type']
00088                 dev.uuid = str(dev_id)
00089                 dev.data.append(rocon_std_msgs.KeyValue('data', ''))
00090                 dev.data.append(rocon_std_msgs.KeyValue('guid', str(dev_id)))
00091                 msgs.append(dev)
00092         return msgs
00093 
00094     def _request_reset(self):
00095         for dev_msg in self._devices_msgs:
00096             for data in dev_msg.data:
00097                 if data.key == "guid":
00098                     dev_guid = data.value
00099                     request_url = "%s/%s?user_access_token=%s" % (self._endpoint_url, 'device/' + dev_guid + '/callback', self._config['access_token'])
00100                     if self._is_register_callback(dev_guid):
00101                         resp = requests.delete(url=request_url)
00102                         if resp is not None and resp.status_code == 200:
00103                             result = json.loads(resp.text)
00104                         if 'result' in result.keys():
00105                             if result['result'] == 0:
00106                                 return False
00107         return True
00108 
00109     def request_configuration_update(self, config):
00110         self._init_device_list()
00111         return self._request_register_callback(config)
00112 
00113     def convert_post_to_devices_msg(self, post):
00114         device_data = post
00115         dev_msgs = rocon_device_msgs.Devices()
00116         for msg in self._devices_msgs:
00117             if msg.uuid == device_data['GUID']:
00118                 for msg_data in msg.data:
00119                     if 'data' == msg_data.key and 'DA' in device_data.keys():
00120                         msg_data.value = device_data['DA']
00121                     dev_msgs.devices.append(msg)
00122             elif msg.uuid == (device_data['GUID'] + '_' + device_data['DA']):
00123                 for msg_data in msg.data:
00124                     if 'data' == msg_data.key and 'DA' in device_data.keys():
00125                         msg_data.value = 'on'
00126                 dev_msgs.devices.append(msg)
00127 
00128         return dev_msgs
00129 
00130     def _is_register_callback(self, device_guid):
00131         request_url = "%s/%s?user_access_token=%s" % (self._endpoint_url, 'device/' + device_guid + '/callback', self._config['access_token'])
00132         resp = requests.get(url=request_url)
00133         is_register_callback = False
00134         if resp is not None and resp.status_code == 200:
00135             dev_resp = json.loads(str(resp.text))
00136             if 'result' in dev_resp.keys():
00137                 if dev_resp['result'] == 1:
00138                     is_register_callback = True
00139         return is_register_callback
00140 
00141     def _init_device_list(self):
00142         self._devices_msgs = self._get_device_list()
00143 
00144     def _get_device_list(self):
00145 
00146         devices_msgs = []
00147         request_url = "%s/%s?user_access_token=%s" % (self._endpoint_url, 'devices', self._config['access_token'])
00148         resp = requests.get(url=request_url)
00149         if resp is not None and resp.status_code == 200:
00150             dev_resp = json.loads(str(resp.text))
00151             if 'data' in dev_resp.keys():
00152                 devices_msgs = self._convert_to_device_msgs(dev_resp['data'])
00153         return devices_msgs
00154 
00155     def _request_register_callback(self, config):
00156         callback_url = 'http://%s:%s/devices' % (str(config['address']), str(config['port']))
00157         for dev_msg in self._devices_msgs:
00158             dev_guid = ''
00159             for dev_msg_data in dev_msg.data:
00160                 if dev_msg_data.key == 'guid':
00161                     dev_guid = dev_msg_data.value
00162                     break
00163             if dev_guid == '':
00164                 continue
00165             else:
00166                 request_url = "%s/%s?user_access_token=%s" % (self._endpoint_url, 'device/' + dev_guid + '/callback', self._config['access_token'])
00167                 data = '{"url":"' + callback_url + '"}'
00168                 headers = {'Content-Type': 'application/json', "Accept": "text/plain"}
00169                 if self._is_register_callback(dev_guid):
00170                     resp = requests.put(url=request_url, data=data, headers=headers)
00171                 else:
00172                     resp = requests.post(url=request_url, data=data, headers=headers)
00173                 if resp is not None and resp.status_code == 200:
00174                     result = json.loads(resp.text)
00175                     if 'result' in result.keys():
00176                         if result['result'] == 0:
00177                             return False, '%s callback url register fails' % dev_msg.label
00178         return True, 'Success'
00179 
00180     def _get_endpoint_url(self):
00181         endpoint_url = 'https://%s' % str(self._config['api'])
00182         return endpoint_url
00183 
00184 if __name__ == '__main__':
00185     rospy.init_node('ninjablock_bridge')
00186 
00187     local_address = rospy.get_param('~local_address')
00188     local_port = rospy.get_param('~local_port')
00189     global_address = rospy.get_param('~global_address')
00190     global_port = rospy.get_param('~global_port')
00191 
00192     connector = NinjaBlockConnector()
00193     bridge = RoconIOTBridge(local_address, local_port, global_address, global_port, connector)
00194 
00195     bridge.loginfo("Initilialised")
00196     bridge.spin()
00197     bridge.loginfo("Bye Bye")


rocon_ninjablock_bridge
Author(s): Dongwook Lee
autogenerated on Thu Jun 6 2019 17:58:49