def send_alldevices(self): """ This method send IoT Box and devices informations to Odoo database """ server = helpers.get_odoo_server_url() if server: subject = helpers.read_file_first_line('odoo-subject.conf') if subject: domain = helpers.get_ip().replace('.', '-') + subject.strip('*') else: domain = helpers.get_ip() iot_box = { 'name': socket.gethostname(), 'identifier': helpers.get_mac_address(), 'ip': domain, 'token': helpers.get_token(), 'version': helpers.get_version() } devices_list = {} for device in iot_devices: identifier = iot_devices[device].device_identifier devices_list[identifier] = { 'name': iot_devices[device].device_name, 'type': iot_devices[device].device_type, 'manufacturer': iot_devices[device].device_manufacturer, 'connection': iot_devices[device].device_connection, } data = { 'params': { 'iot_box': iot_box, 'devices': devices_list, } } # disable certifiacte verification urllib3.disable_warnings() http = urllib3.PoolManager(cert_reqs='CERT_NONE') try: http.request('POST', server + "/iot/setup", body=json.dumps(data).encode('utf8'), headers={ 'Content-type': 'application/json', 'Accept': 'text/plain' }) except Exception as e: _logger.error('Could not reach configured server') _logger.error('A error encountered : %s ' % e) else: _logger.warning('Odoo server not set')
def load_certificate(): """ Send a request to Odoo with customer db_uuid and enterprise_code to get a true certificate """ db_uuid = read_file_first_line('odoo-db-uuid.conf') enterprise_code = read_file_first_line('odoo-enterprise-code.conf') if db_uuid and enterprise_code: url = 'https://www.odoo.com/odoo-enterprise/iot/x509' data = { 'params': { 'db_uuid': db_uuid, 'enterprise_code': enterprise_code } } urllib3.disable_warnings() http = urllib3.PoolManager(cert_reqs='CERT_NONE') response = http.request( 'POST', url, body = json.dumps(data).encode('utf8'), headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} ) result = json.loads(response.data.decode('utf8'))['result'] if result: write_file('odoo-subject.conf', result['subject_cn']) subprocess.call(["sudo", "mount", "-o", "remount,rw", "/"]) subprocess.call(["sudo", "mount", "-o", "remount,rw", "/root_bypass_ramdisks/"]) Path('/etc/ssl/certs/nginx-cert.crt').write_text(result['x509_pem']) Path('/root_bypass_ramdisks/etc/ssl/certs/nginx-cert.crt').write_text(result['x509_pem']) Path('/etc/ssl/private/nginx-cert.key').write_text(result['private_key_pem']) Path('/root_bypass_ramdisks/etc/ssl/private/nginx-cert.key').write_text(result['private_key_pem']) subprocess.call(["sudo", "mount", "-o", "remount,ro", "/"]) subprocess.call(["sudo", "mount", "-o", "remount,ro", "/root_bypass_ramdisks/"]) subprocess.call(["sudo", "mount", "-o", "remount,rw", "/root_bypass_ramdisks/etc/cups"]) subprocess.check_call(["sudo", "service", "nginx", "restart"])
def check_git_branch(): """ Check if the local branch is the same than the connected Odoo DB and checkout to match it if needed. """ server = get_odoo_server_url() if server: urllib3.disable_warnings() http = urllib3.PoolManager(cert_reqs='CERT_NONE') try: response = http.request( 'POST', server + "/web/webclient/version_info", body='{}', headers={'Content-type': 'application/json'}) if response.status == 200: git = [ 'git', '--work-tree=/home/pi/odoo/', '--git-dir=/home/pi/odoo/.git' ] db_branch = json.loads( response.data)['result']['server_serie'].replace('~', '-') if not subprocess.check_output( git + ['ls-remote', 'origin', db_branch]): db_branch = 'master' local_branch = subprocess.check_output( git + ['symbolic-ref', '-q', '--short', 'HEAD']).decode( 'utf-8').rstrip() if db_branch != local_branch: subprocess.check_call( ["sudo", "mount", "-o", "remount,rw", "/"]) subprocess.check_call([ "rm", "-rf", "/home/pi/odoo/addons/hw_drivers/iot_handlers/drivers/*" ]) subprocess.check_call([ "rm", "-rf", "/home/pi/odoo/addons/hw_drivers/iot_handlers/interfaces/*" ]) subprocess.check_call(git + ['branch', '-m', db_branch]) subprocess.check_call( git + ['remote', 'set-branches', 'origin', db_branch]) os.system( '/home/pi/odoo/addons/point_of_sale/tools/posbox/configuration/posbox_update.sh' ) subprocess.check_call( ["sudo", "mount", "-o", "remount,ro", "/"]) subprocess.check_call([ "sudo", "mount", "-o", "remount,rw", "/root_bypass_ramdisks/etc/cups" ]) except Exception as e: _logger.error('Could not reach configured server') _logger.error('A error encountered : %s ' % e)
def send_alldevices(self): """ This method send IoT Box and devices informations to Odoo database """ server = get_odoo_server_url() if server: iot_box = { 'name': socket.gethostname(), 'identifier': get_mac_address(), 'ip': get_ip(), 'token': get_token(), 'version': get_version() } devices_list = {} for device in iot_devices: identifier = iot_devices[device].device_identifier devices_list[identifier] = { 'name': iot_devices[device].device_name, 'type': iot_devices[device].device_type, 'connection': iot_devices[device].device_connection, } data = { 'params': { 'iot_box' : iot_box, 'devices' : devices_list, } } # disable certifiacte verification urllib3.disable_warnings() http = urllib3.PoolManager(cert_reqs='CERT_NONE') try: http.request( 'POST', server + "/iot/setup", body = json.dumps(data).encode('utf8'), headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} ) except Exception as e: _logger.error('Could not reach configured server') _logger.error('A error encountered : %s ' % e) else: _logger.warning('Odoo server not set')
def load_url(self): if helpers.get_odoo_server_url(): # disable certifiacte verification urllib3.disable_warnings() http = urllib3.PoolManager(cert_reqs='CERT_NONE') try: response = http.request('GET', "%s/iot/box/%s/screen_url" % (helpers.get_odoo_server_url(), helpers.get_mac_address())) urls = json.loads(response.data.decode('utf8')) return self.update_url(urls[self.device_identifier]) except json.decoder.JSONDecodeError: return self.update_url(response.get(data.decode('utf8'), False)) except Exception: pass return self.update_url()
def load_url(self): url = None if helpers.get_odoo_server_url(): # disable certifiacte verification urllib3.disable_warnings() http = urllib3.PoolManager(cert_reqs='CERT_NONE') try: response = http.request('GET', "%s/iot/box/%s/display_url" % (helpers.get_odoo_server_url(), helpers.get_mac_address())) if response.status == 200: data = json.loads(response.data.decode('utf8')) url = data[self.device_identifier] except json.decoder.JSONDecodeError: url = response.data.decode('utf8') except Exception: pass return self.update_url(url)
def check_image(): """ Check if the current image of IoT Box is up to date """ url = 'https://nightly.odoo.com/master/iotbox/SHA1SUMS.txt' urllib3.disable_warnings() http = urllib3.PoolManager(cert_reqs='CERT_NONE') response = http.request('GET', url) checkFile = {} valueActual = '' for line in response.data.decode().split('\n'): if line: value, name = line.split(' ') checkFile.update({value: name}) if name == 'iotbox-latest.zip': valueLastest = value elif name == get_img_name(): valueActual = value if valueActual == valueLastest: return False version = checkFile.get(valueLastest, 'Error').replace('iotboxv', '').replace('.zip', '').split('_') return {'major': version[0], 'minor': version[1]}
def get_homepage_data(self): hostname = str(socket.gethostname()) mac = get_mac() h = iter(hex(mac)[2:].zfill(12)) ssid = subprocess.check_output('iwconfig 2>&1 | grep \'ESSID:"\' | sed \'s/.*"\\(.*\\)"/\\1/\'', shell=True).decode('utf-8').rstrip() wired = subprocess.check_output('cat /sys/class/net/eth0/operstate', shell=True).decode('utf-8').strip('\n') if wired == 'up': network = 'Ethernet' elif ssid: if self.get_ip_iotbox() == '10.11.12.1': network = 'Wifi access point' else: network = 'Wifi : ' + ssid else: network = 'Not Connected' pos_device = self.get_pos_device_status() iot_device = [] for status in pos_device: if pos_device[status]['status'] == 'connected': iot_device.append({ 'name': status, 'type': 'device', 'message': ' '.join(pos_device[status]['messages']) }) hdmi_name = subprocess.check_output('tvservice -n', shell=True).decode('utf-8') if hdmi_name.find('=') != -1: hdmi_name = hdmi_name.split('=')[1] hdmi_message = subprocess.check_output('tvservice -s', shell=True).decode('utf-8') iot_device.append({ 'name': 'display : ' + hdmi_name, 'type': 'device', 'message': hdmi_message }) try: f = open('/tmp/devices', 'r') for line in f: url = 'http://' + self.get_ip_iotbox() + ':8069/hw_drivers/driverdetails/' + line.split('|')[0] http = urllib3.PoolManager() value = '' try: req = http.request('GET', url) except: req = '' if req: value = req.data.decode('utf-8') iot_device.append({ 'name': line.split('|')[1], 'message': line.split('|')[0] + ' : ' + value, 'type': 'device', }) f.close() except: pass try: f = open('/tmp/printers', 'r') for line in f: iot_device.append({ 'name': line, 'type': 'printer', }) f.close() except: pass return { 'hostname': hostname, 'ip': self.get_ip_iotbox(), 'mac': ":".join(i + next(h) for i in h), 'iot_device_status': iot_device, 'server_status': self.get_server_status() or 'Not Configured', 'network_status': network, }
def get_homepage_data(self): hostname = str(socket.gethostname()) mac = get_mac() h = iter(hex(mac)[2:].zfill(12)) ssid = subprocess.check_output( 'iwconfig 2>&1 | grep \'ESSID:"\' | sed \'s/.*"\\(.*\\)"/\\1/\'', shell=True).decode('utf-8').rstrip() wired = subprocess.check_output('cat /sys/class/net/eth0/operstate', shell=True).decode('utf-8').strip('\n') if wired == 'up': network = 'Ethernet' elif ssid: if self.get_ip_iotbox() == '10.11.12.1': network = 'Wifi access point' else: network = 'Wifi : ' + ssid else: network = 'Not Connected' pos_device = self.get_pos_device_status() iot_device = [] for status in pos_device: if pos_device[status]['status'] == 'connected': iot_device.append({ 'name': status, 'type': 'device', 'message': ' '.join(pos_device[status]['messages']) }) hdmi_name = subprocess.check_output('tvservice -n', shell=True).decode('utf-8') if hdmi_name.find('=') != -1: hdmi_name = hdmi_name.split('=')[1] hdmi_message = subprocess.check_output('tvservice -s', shell=True).decode('utf-8') iot_device.append({ 'name': 'display : ' + hdmi_name, 'type': 'device', 'message': hdmi_message }) try: f = open('/tmp/devices', 'r') for line in f: url = 'http://' + self.get_ip_iotbox( ) + ':8069/hw_drivers/driverdetails/' + line.split('|')[0] http = urllib3.PoolManager() value = '' try: req = http.request('GET', url) except: req = '' if req: value = req.data.decode('utf-8') iot_device.append({ 'name': line.split('|')[1], 'message': line.split('|')[0] + ' : ' + value, 'type': 'device', }) f.close() except: pass try: f = open('/tmp/printers', 'r') for line in f: iot_device.append({ 'name': line, 'type': 'printer', }) f.close() except: pass return { 'hostname': hostname, 'ip': self.get_ip_iotbox(), 'mac': ":".join(i + next(h) for i in h), 'iot_device_status': iot_device, 'server_status': self.get_server_status() or 'Not Configured', 'network_status': network, }
def get_details(self): http = urllib3.PoolManager() URL = 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVin/' + str( self.vin_number) + '?format=json&modelyear=2011' datas = http.request('GET', URL) datas = json.loads(datas.data.decode('utf-8')) datas = datas.get('Results') details = {} for dicts in datas: if dicts.get('VariableId') == 26: details['brand'] = dicts.get('Value') if dicts.get('VariableId') == 28: details['model_id'] = dicts.get('Value') if dicts.get('VariableId') == 29: details['model_year'] = dicts.get('Value') if dicts.get('VariableId') == 21: details['engine_power'] = dicts.get('Value') if dicts.get('VariableId') == 37: details['transmission_style'] = dicts.get('Value') if dicts.get('VariableId') == 18: details['engine_model'] = dicts.get('Value') if dicts.get('VariableId') == 9: details['no_of_cylinder'] = dicts.get('Value') if dicts.get('VariableId') == 33: details['no_of_seats'] = dicts.get('Value') if dicts.get('VariableId') == 14: details['no_of_doors'] = dicts.get('Value') if dicts.get('VariableId') == 2: details['battery_type'] = dicts.get('Value') if dicts.get('VariableId') == 58: details['battery_voltage'] = dicts.get('Value') if dicts.get('VariableId') == 59: details['battery_energy'] = dicts.get('Value') if dicts.get('VariableId') == 24: details['fuel_type'] = dicts.get('Value') brand_id = 0 try: if details.get('brand'): nameupperc = details.get('brand') nameproper = nameupperc[0:1] + nameupperc[1:].lower() brand_id = self.env['fleet.vehicle.model.brand'].search( [('name', '=', nameproper)], limit=1).id if brand_id: pass else: try: brand_id = self.env[ 'fleet.vehicle.model.brand'].create( {'name': nameproper}) except: pass if details.get('engine_power'): self.horsepower = int(float(details.get('engine_power'))) if details.get('engine_model'): self.engine_size = str(details.get('engine_model')) if details.get('no_of_cylinder'): self.cylinders = int(details.get('no_of_cylinder')) if details.get('no_of_seats'): self.seats = int(details.get('no_of_seats')) if details.get('no_of_doors'): self.doors = int(details.get('no_of_doors')) if details.get('battery_type'): self.battery_type = str(details.get('battery_type')) if details.get('battery_voltage'): self.battery_voltage = str(details.get('battery_voltage')) if details.get('battery_energy'): self.battery_energy = str(details.get('battery_energy')) except: pass try: if details.get('fuel_type'): fuel_type = str(details['fuel_type']) try: self.fuel_type = fuel_type.lower() except: pass if details.get('model_id'): model = details.get('model_id') print("model name ", model) model_id = self.env["fleet.vehicle.model"].search( [('name', '=', model)], limit=1).id if model_id: self.model_id = model_id else: self.model_id = self.env["fleet.vehicle.model"].create({ 'name': model, 'brand_id': brand_id.id }) if details.get('model_year'): self.model_year = details.get('model_year') except: pass return { 'type': 'ir.actions.client', 'tag': 'reload', }
def send_iot_box_device(send_printer): maciotbox = subprocess.check_output("/sbin/ifconfig eth0 |grep -Eo ..\(\:..\){5}", shell=True).decode('utf-8').split('\n')[0] server = "" # read from file try: f = open('/home/pi/odoo-remote-server.conf', 'r') for line in f: server += line f.close() except: #In case the file does not exist server='' server = server.split('\n')[0] if server: url = server + "/iot/setup" interfaces = ni.interfaces() for iface_id in interfaces: iface_obj = ni.ifaddresses(iface_id) ifconfigs = iface_obj.get(ni.AF_INET, []) for conf in ifconfigs: if conf.get('addr') and conf.get('addr') != '127.0.0.1': ips = conf.get('addr') break # Build device JSON devicesList = {} for path in drivers: device_name = drivers[path].get_name() device_connection = drivers[path].get_connection() identifier = path.split('_')[0] + '_' + path.split('_')[1] devicesList[identifier] = {'name': device_name, 'type': 'device', 'connection': device_connection} # Build camera JSON try: cameras = subprocess.check_output("v4l2-ctl --list-devices", shell=True).decode('utf-8').split('\n\n') for camera in cameras: if camera: camera = camera.split('\n\t') serial = re.sub('[^a-zA-Z0-9 ]+', '', camera[0].split(': ')[0]).replace(' ','_') devicesList[serial] = { 'name': camera[0].split(': ')[0], 'connection': 'direct', 'type': 'camera' } except: pass # Build printer JSON printerList = {} if send_printer: printers = subprocess.check_output("sudo lpinfo -lv", shell=True).decode('utf-8').split('Device') for printer in printers: printerTab = printer.split('\n') if printer and printerTab[4].split('=')[1] != ' ': device_connection = printerTab[1].split('= ')[1] model = '' for device_id in printerTab[4].split('= ')[1].split(';'): if any(x in device_id for x in ['MDL','MODEL']): model = device_id.split(':')[1] name = printerTab[2].split('= ')[1] serial = re.sub('[^a-zA-Z0-9 ]+', '', model).replace(' ','_') identifier = '' if device_connection == 'direct': identifier = serial + '_' + maciotbox #name + macIOTBOX elif device_connection == 'network' and 'socket' in printerTab[0]: socketIP = printerTab[0].split('://')[1] macprinter = subprocess.check_output("arp -a " + socketIP + " |awk NR==1'{print $4}'", shell=True).decode('utf-8').split('\n')[0] identifier = macprinter # macPRINTER elif device_connection == 'network' and 'dnssd' in printerTab[0]: hostname_printer = subprocess.check_output("ippfind -n \"" + model + "\" | awk \'{split($0,a,\"/\"); print a[3]}\' | awk \'{split($0,b,\":\"); print b[1]}\'", shell=True).decode('utf-8').split('\n')[0] if hostname_printer: macprinter = subprocess.check_output("arp -a " + hostname_printer + " |awk NR==1'{print $4}'", shell=True).decode('utf-8').split('\n')[0] identifier = macprinter # macprinter identifier = identifier.replace(':','_') if identifier and identifier not in printerList: printerList[identifier] = { 'name': model, 'connection': device_connection, 'type': 'printer' } # install these printers try: ppd = subprocess.check_output("sudo lpinfo -m |grep '" + model + "'", shell=True).decode('utf-8').split('\n') if len(ppd) > 2: subprocess.call("sudo lpadmin -p '" + identifier + "' -E -v '" + printerTab[0].split('= ')[1] + "'", shell=True) else: subprocess.call("sudo lpadmin -p '" + identifier + "' -E -v '" + printerTab[0].split('= ')[1] + "' -m '" + ppd[0].split(' ')[0] + "'", shell=True) except: subprocess.call("sudo lpadmin -p '" + identifier + "' -E -v '" + printerTab[0].split('= ')[1] + "'", shell=True) subprocess.call('> /tmp/printers', shell=True) for printer in printerList: subprocess.call('echo "' + printerList[printer]['name'] + '" >> /tmp/printers', shell=True) if devicesList: subprocess.call('> /tmp/devices', shell=True) for device in devicesList: subprocess.call('echo "' + str(device) + '|' + devicesList[device]['name'] + '" >> /tmp/devices', shell=True) #build JSON with all devices hostname = subprocess.check_output('hostname').decode('utf-8').split('\n')[0] token = "" # read from file try: f = open('/home/pi/token', 'r') for line in f: token += line f.close() except: #In case the file does not exist token='' token = token.split('\n')[0] data = {'name': hostname,'identifier': maciotbox, 'ip': ips, 'token': token} devicesList.update(printerList) data['devices'] = devicesList data_json = json.dumps(data).encode('utf8') headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} http = urllib3.PoolManager() req = False try: req = http.request('POST', url, body=data_json, headers=headers) except: _logger.warning('Could not reach configured server')