from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from cocktails.models import Cocktail
from alcohol.models import Alcohol
from drink_categories.models import DrinkCategory
from blogs.models import Blog
from events.models import Event
from event_types.models import EventType
from counties.models import County
from categories.models import Category
from clubs.models import Club
from drink_categories.models import DrinkCategory
from genres.models import Genre
from datetime import datetime, date
from django.db.models import Q
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator

def home_page(request):
    brunch = Category.objects.filter(name='Brunch')
    vodka = Cocktail.objects.filter(alcohol__name='Vodka')
    whiskey = Cocktail.objects.filter(alcohol__name='Whiskey')
    gin = Cocktail.objects.filter(alcohol__name='Gin')
    rum = Cocktail.objects.filter(alcohol__name='Rum')
    tequila = Cocktail.objects.filter(alcohol__name='Tequila')
    beer_wine = Cocktail.objects.filter(categories__name='Beer & Wine').order_by('-updated_at')
    flavor = Cocktail.objects.filter(categories__name='Flavor').order_by('-updated_at')
    posts = Blog.objects.filter(categories='1').order_by('-updated_at')[:3]
    # data to be displayed in filter section menu
    menu_cocktail_categories = DrinkCategory.objects.all().order_by('-created_at')
    genres = Genre.objects.all().order_by('name').filter(is_published=True)
    event_categories = Category.objects.filter(name='Brunch').order_by('name')
    #   display all cocktails belonging to one category
    beers = DrinkCategory.objects.filter(name='Beer & Wine')
    vodka_cocktails = Alcohol.objects.filter(name='Vodka')
    whiskey_cocktails = Alcohol.objects.filter(name='Whiskey')
    gin_cocktails = Alcohol.objects.filter(name='Gin')
    rum_cocktails = Alcohol.objects.filter(name='Rum')
    tequila_cocktails = Alcohol.objects.filter(name='Tequila')
    flavors = DrinkCategory.objects.filter(name='Flavor')

    context = {
        "brunchs": brunch,
        'whiskey': whiskey,
        'vodka': vodka,
        'beer_wine': beer_wine,
        'gin': gin,
        'rum': rum,
        'tequila': tequila,
        'beers': beers,
        'flavor': flavor,
        'vodka_cocktails': vodka_cocktails,
        'posts': posts,
        'menu_cocktail_categories': menu_cocktail_categories,
        "event_categories": event_categories,
        'whiskey_cocktails': whiskey_cocktails,
        'gin_cocktails': gin_cocktails,
        'rum_cocktails': rum_cocktails,
        'tequila_cocktails': tequila_cocktails,
        'flavors': flavors,
    }
    return render(request, "pages/index.html", context)

def explore_page(request):
    #display all cover images in detailed category
    cover_image = Event.objects.filter(is_published=True).exclude(cover_image__isnull=True).exclude(cover_image__exact='').order_by('event_date')
    clubs = Club.objects.filter(is_published=True).order_by('name')
    happy_hour = Event.objects.filter(categories='6', is_published=True).order_by('event_date')
    tonight = Event.objects.filter(event_date__date=date.today(), is_published=True)
    classics = Cocktail.objects.filter(categories='1').order_by('-updated_at')
    this_weekend = Event.objects.filter(Q(event_date__week_day=1) | Q(event_date__week_day=7), is_published=True)
    trending = Event.objects.filter(event_type='2', is_published=True).order_by('event_date')
    # data to be displayed in filter section menu
    menu_cocktail_categories = DrinkCategory.objects.all().order_by('-created_at')
    genres = Genre.objects.filter(is_published=True).order_by('name')
    event_categories = Category.objects.filter(name='Brunch').order_by('name')
    counties = County.objects.all().order_by('-created_at')
    brunch_events = Event.objects.filter(categories='4').order_by('event_date')

    context = {
        "covers": cover_image,
        "clubs": clubs,
        "happy_hour": happy_hour,
        "tonight": tonight,
        'classics': classics,
        "this_weekend": this_weekend,
        "trending": trending,
        'genres': genres,
        "event_categories": event_categories,
        "counties": counties,
        'menu_cocktail_categories': menu_cocktail_categories,
        "brunch_events": brunch_events,
    }
    return render(request, "pages/explore.html", context)

def about_page(request):
    clubs = Club.objects.filter(is_published=True).order_by('name')

    context = {
        "clubs": clubs,
    }
    return render(request, "pages/about.html", context)

def terms_and_conditions_page(request):
    context = {
    }
    return render(request, "pages/terms-and-conditions.html", context)

def server_error(request):
    context = {
    }
    return render(request, 'pages/500.html', context)

def not_found(request, exception=None):
    context = {
    }
    return render(request, 'pages/404.html', context)

def permission_denied(request, exception=None):
    context = {
    }
    return render(request, 'pages/403.html', context)

def bad_request(request, exception=None):
    context = {
    }
    return render(request, 'pages/400.html', context)


# -*- coding: utf-8 -*-

import json

from ..base.multi_downloader import MultiDownloader

class FastixRu(MultiDownloader):
    __name__ = "FastixRu"
    __type__ = "downloader"
    __version__ = "0.22"
    __status__ = "testing"

    __pattern__ = r"http://(?:www\.)?fastix\.(ru|it)/file/\w{24}"
    __config__ = [
        ("enabled", "bool", "Activated", True),
        ("use_premium", "bool", "Use premium account if available", True),
        ("fallback", "bool", "Fallback to free download if premium fails", False),
        ("chk_filesize", "bool", "Check file size", True),
        ("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10),
        ("revert_failed", "bool", "Revert to standard download if fails", True),
    ]

    __description__ = """Fastix multi-downloader plugin"""
    __license__ = "GPLv3"
    __authors__ = [("Massimo Rosamilia", "max@spiritix.eu")]

    def setup(self):
        self.chunk_limit = 3

    def handle_premium(self, pyfile):
        self.data = self.load(
            "http://fastix.ru/api_v2/",
            get={
                "apikey": self.account.get_data("apikey"),
                "sub": "getdirectlink",
                "link": pyfile.url,
            },
        )
        data = json.loads(self.data)

        self.log_debug("Json data", data)

        if 'error":true' in self.data:
            self.offline()
        else:
            self.link = data["downloadlink"]


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Address',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('address_1', models.CharField(max_length=200)),
                ('address_2', models.CharField(max_length=200)),
                ('address_3', models.CharField(max_length=200)),
                ('town', models.CharField(max_length=200)),
                ('post_code', models.CharField(max_length=10)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Company',
            fields=[
                ('address_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='company.Address')),
                ('name', models.CharField(max_length=200)),
            ],
            options={
            },
            bases=('company.address',),
        ),
        migrations.CreateModel(
            name='Contact',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200, blank=True)),
                ('number', models.CharField(max_length=200, blank=True)),
                ('type', models.CharField(default=b'TEL', max_length=3, choices=[(b'TEL', b'Telephone'), (b'MOB', b'Mobile'), (b'FAX', b'Fax')])),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='CompanyContact',
            fields=[
                ('contact_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='company.Contact')),
                ('is_primary', models.BooleanField(default=False)),
                ('company', models.ForeignKey(to='company.Company')),
            ],
            options={
            },
            bases=('company.contact',),
        ),
        migrations.CreateModel(
            name='County',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Site',
            fields=[
                ('address_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='company.Address')),
                ('company', models.ForeignKey(to='company.Company')),
            ],
            options={
            },
            bases=('company.address',),
        ),
        migrations.CreateModel(
            name='SiteContact',
            fields=[
                ('contact_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='company.Contact')),
                ('is_primary', models.BooleanField(default=False)),
                ('site', models.ForeignKey(to='company.Site')),
            ],
            options={
            },
            bases=('company.contact',),
        ),
        migrations.AddField(
            model_name='address',
            name='county',
            field=models.ForeignKey(to='company.County'),
            preserve_default=True,
        ),
    ]


import json
import glob

folder_path = "audios"
list_jsons = [x for x in glob.glob(f"{folder_path}/*.json")]
list_audios = [x for x in glob.glob(f"{folder_path}/*.wav")]

list_jsons = sorted(list_jsons, key=lambda x: int(x.split(".")[0].split(" ")[1]))
list_audios = sorted(list_audios, key=lambda x: int(x.split(".")[0].split(" ")[1]))

error = False
if len(list_jsons) != len(list_audios):
    print("ERROR")

text_file = f'{folder_path}/output_text.txt'

print(len(list_jsons))

with open(text_file, mode='w', encoding='utf-8') as output_file:
    for audio_file, json_file in zip(list_audios, list_jsons):
        with open(json_file, encoding='utf-8') as json_data:
            print(audio_file, json_file)
            data = json.load(json_data)
            text = data['results']['transcripts'][0]['transcript']
            output_file.write(f"{audio_file} : {text}\n")


class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        # Store rows and cols
        rows=len(board)
        cols=len(board[0])
        # path storing the visited celss. Prevents visiting visited cell
        found = False
        pathway=set()
        def dfs(r,c,i):
            # if word found
            if i == len(word):
                found = True
                return True
            # if the conditions fall apart
            if (r<0 or
               c<0 or
               r>=rows or
               c>=cols or
               word[i] != board[r][c] or
               (r,c) in pathway): return False

            pathway.add((r,c))

            # check top right bottom left
            result = (dfs(r+1, c, i+1 ) or
                     dfs(r-1, c, i+1 ) or
                     dfs(r, c+1, i+1 ) or
                     dfs(r, c-1, i+1 ) )
            # reste path
            pathway.remove((r,c))
            #return result
            return result
        for elemR in range(0,rows):
            for elemC in range(0,cols):
                if dfs(elemR, elemC, 0): return True
        return False


from PIL import Image

def rgb_to_hex(r, g, b, a):
    return '#{:02x}{:02x}{:02x}{:02x}'.format(r, g, b, a)

_width = 0.66
_height = 1.117

#optimization alignment
_WIDTH_SIZE10 = 0.0287
_HEIGHT_SIZE10 = -0.4525

_width4x = _WIDTH_SIZE10 * 3
_height4x = _HEIGHT_SIZE10 * 3

im = Image.open(input(),'r')
im_width = im.width
im_height = im.height

image_data = list(im.getdata())

size = 10
xoffset = 0
yoffset = 0
character = '_'

header = '<align=left><line-height=0%><width=0><color=#000>\n'

optimized_pixels = [(-1,-1)]
last_was_optimized = False

optimized2x_once = False
optimized2x_once_offset = 0

sorted_pixels = [[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1],[-1]]
optimized_pixels = []

print("{", "{0}, {1}, ".format(im_width,im_height), "{",end="")
for index, pixel in enumerate(image_data):
    print("RGBA({0}, {1}, {2}, {3})".format(pixel[0],pixel[1],pixel[2],pixel[3]), end=",")
print("}","}")

breakpoint()

done = False
while done == False:
    new_pixel = False
    for index, pixel in enumerate(image_data):

        if ((pixel[3]) < 128):
            continue

        pixel_is_sorted_or_optimized = False
        for sorted_pixel_sizes in sorted_pixels:
            for sorted_pixel in sorted_pixel_sizes:
                if sorted_pixel == index:
                    pixel_is_sorted_or_optimized = True
                    break
            if pixel_is_sorted_or_optimized == True:
                break
        if pixel_is_sorted_or_optimized == True:
            continue
        for optimized_pixel in optimized_pixels:
            if optimized_pixel == index:
                pixel_is_sorted_or_optimized = True
                break
        if pixel_is_sorted_or_optimized == True:
            continue

        new_pixel = True

        hexcol = rgb_to_hex(pixel[0], pixel[1], pixel[2], pixel[3])

        if index + im_width > im_width*im_height - 1:
            sorted_pixels[0].append(index)
        elif hexcol != rgb_to_hex(image_data[index+im_width][0], image_data[index+im_width][1], image_data[index+im_width][2], image_data[index+im_width][3]):
            sorted_pixels[0].append(index)
        else:
            sorted_size = 1
            while index + im_width * sorted_size + sorted_size-1 < im_width*im_height:
                wrong_color = False

                to_be_optimized = []
                #vertical check
                for i in range(sorted_size+1):
                    check_index = index + sorted_size-1 + i * im_width
                    if hexcol != rgb_to_hex(image_data[check_index][0],image_data[check_index][1],image_data[check_index][2],image_data[check_index][3]):
                        wrong_color = True
                        break
                    if check_index != index:
                        to_be_optimized.append(check_index)

                #horizontal check
                for i in range(sorted_size):
                    check_index = index + (sorted_size-1) * im_width + i
                    if hexcol != rgb_to_hex(image_data[check_index][0],image_data[check_index][1],image_data[check_index][2],image_data[check_index][3]):
                        wrong_color = True
                        break
                    if check_index != index:
                        to_be_optimized.append(check_index)

                if wrong_color:
                    break
                else:
                    for idx in to_be_optimized:
                        optimized_pixels.append(idx)

                sorted_size += 1
            sorted_pixels[sorted_size-1].append(index)

    if new_pixel == False:
        done = True

for pixel_array in sorted_pixels:
    pixel_array.sort()
optimized_pixels.sort()

file_limit_reached = False
file_count = 1
tmp_char_limit = 4096
chars_per_pixel = 2

force_voffset = False
force_mark = False
chars_parsed = 0

last_color = 'none'
last_index = -1
last_size = -1

file = open("tmp_out_part1.txt", "w")
print("tmp_out_part1.txt")
for sorted_size, pixel_index_array in enumerate(sorted_pixels):
    out = ''
    if len(pixel_index_array) < 2:
        continue

    if file_limit_reached == True:
        file.close()
        file_count += 1
        file = open("tmp_out_part" + str(file_count) + '.txt', "w")
        print("tmp_out_part" + str(file_count) + '.txt')
        out = header
        force_voffset = True
        force_mark = True

    if sorted_size == 0:
        out += '<size=' + str(size) + '>'
    else:
        out += '<size=' + str(size * (sorted_size+1)) + '>'

    for index in pixel_index_array:
        if index == -1:
            continue

        if int(last_index / im_width) < int(index / im_width) or force_voffset:
            new_voffset = round((int( index / im_width - 1 ) * _height )*-1 + yoffset, 4)
            out += '<voffset=' + str(new_voffset) + 'em>'
            force_voffset = False

        hexcol = rgb_to_hex(image_data[index][0], image_data[index][1], image_data[index][2], image_data[index][3])

        if (last_color != hexcol or force_mark):
            out += '<mark=' + hexcol + '>'
            last_color = hexcol
            force_mark = False

        out += '<pos=' + str(round((( index % im_width ) * 2 + 0 ) * _width + xoffset*2, 4)) + 'em>' + character
        chars_parsed += 1

        if sorted_size == 0:
            out += '<pos=' + str(round((( index % im_width ) * 2 + 1 ) * _width + xoffset*2, 4)) + 'em>' + character
            chars_parsed += 1

        out += '\n'
        file.write(out)
        out = ''
        last_index = index

        if chars_parsed % tmp_char_limit > 1:
            file_limit_reached = False

        if chars_parsed % tmp_char_limit == 1:
            if file_limit_reached == True:
                file_limit_reached = False
            else:
                file_limit_reached = True
        if chars_parsed % tmp_char_limit == 0:
            file_limit_reached = True

file.close()


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This module provides a class for a CAN wrapper for the ADC channels of the MOPS Chip.
It also provides a function for using this server as a command line tool.
Note
----
:Author: Ahmed Qamesh
:Contact: ahmed.qamesh@cern.ch
:Organization: Bergische Universität Wuppertal
"""
# Standard library modules
#from __future__ import annotations
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from configparser import ConfigParser
from typing import *
import time
import datetime
#import asyncio
#from asyncio.tasks import sleep
import sys
import os
from threading import Thread, Event, Lock
import subprocess
import threading
import numpy as np
try:
    from logger_main   import Logger
    from analysis_utils import AnalysisUtils
    from analysis import Analysis
except (ImportError, ModuleNotFoundError):
    from .logger_main   import Logger
    from .analysis_utils import AnalysisUtils
    from .analysis import Analysis
import struct
# Third party modules
from collections import deque, Counter
from tqdm import tqdm
import ctypes as ct
import logging
import queue
from bs4 import BeautifulSoup #virtual env
from typing import List, Any
from random import randint
import uhal

import random
#from csv import writer
logger = Logger().setup_main_logger(name = " Lib Check ",console_loglevel=logging.INFO, logger_file = False)

rootdir = os.path.dirname(os.path.abspath(__file__))
config_dir = "config_files/"
lib_dir = rootdir[:-8]

class UHALWrapper(object):#READSocketcan):#Instead of object

    def __init__(self,
                 file_loglevel=logging.INFO,
                 logdir=None,load_config = False,
                 logfile = None,
                 console_loglevel=logging.INFO,
                 mainWindow= False):

        super(UHALWrapper, self).__init__()  # super keyword to call its methods from a subclass:
        #Initialize a watchdog (to be done)
        #Begin a thread settings (to be done)
        self.sem_read_block = threading.Semaphore(value=0)
        self.sem_recv_block = threading.Semaphore(value=0)
        self.sem_config_block = threading.Semaphore()

        """:obj:`~logging.Logger`: Main logger for this class"""
        if logdir is None:
            #'Directory where log files should be stored'
            logdir = os.path.join(lib_dir, 'log')
        self.logger = Logger().setup_main_logger(name = "UHAL Wrapper",console_loglevel=console_loglevel, logger_file = False)

        if load_config:
           # Read CAN settings from a file
            self.__uri, self.__addressFilePath =   self.load_settings_file()

        # Initialize library and set connection parameters
        self.__canMsgQueue = deque([], 100)  # queue with a size of 100 to queue all the messages in the bus
        self.__uhalMsgQueue = deque([], 100)
        self.__cnt = Counter()
        self.error_counter = 0
        self.__pill2kill = Event()
        self.__lock = Lock()
        self.__hw = None
        self.logger.success('....Done Initialization!')
        self.__address_byte = [0x80, 0x88, 0x90, 0x98, 0x80]
        if logfile is not None:
            ts = os.path.join(logdir, time.strftime('%Y-%m-%d_%H-%M-%S_UHAL_Wrapper.'))
            self.logger.info(f'Existing logging Handler: {ts}'+'log')
            self.logger_file = Logger().setup_file_logger(name = "UHALWrapper",console_loglevel=console_loglevel, logger_file = ts)#for later usage
            self.logger_file.success('....Done Initialization!')

    def set_hw_connection(self):
        self.logger.info(f'Starting a Thread for MOPSHUB')
        self.__uhalMsgThread = Thread(target=self.read_uhal_mopshub_message, args=(["reg0","reg1","reg2"], 0.001,  None))#self.between_thread_callback)
        self.__uhalMsgThread.start()

    def between_thread_callback(self):
        loop = asyncio.new_event_loop()
        loop.run_until_complete(self.call_back_read_uhal_mopshub_message())

    def call_back_read_uhal_mopshub_message(self):
        self.read_uhal_mopshub_message(reg = ["reg0","reg1","reg2"], timeout=0.001, out_msg = None)

    def config_uhal_hardware(self, uri = None, addressFilePath = None):
        if uri is None:
            uri = self.__uri
        if addressFilePath is None:
            addressFilePath = self.__addressFilePath
        hw = uhal.getDevice("mopshub", uri, "file://" + addressFilePath)
        self.set_uhal_hardware(hw)
        self.set_hw_connection()
        return hw

    def get_ual_node(self, hw =None, registerName = None):
        node = hw.getNode(registerName)
        return node

    def load_settings_file(self, file="main_settings.yml"):
        """Load all the information related to the hardware
        Parameters
        ----------
        file : :obj:`str` represents the yaml file name
        """

        filename = lib_dir + config_dir + file
        filename = os.path.join(lib_dir, config_dir + file)
        test_date = time.ctime(os.path.getmtime(filename))
        # Load settings from bus settings file
        self.logger.notice("Loading bus settings from the file %s produced on %s" % (filename, test_date))
        try:
            _channelSettings = AnalysisUtils().open_yaml_file(file=config_dir + "main_settings.yml", directory=lib_dir)
            _uri = _channelSettings['ethernet']["uri"]
            _addressFilePath = _channelSettings['ethernet']["addressFilePath"]
            return _uri,_addressFilePath
        except:
          self.logger.error("uri %s settings Not found" % (_uri))
          return None,None

    def read_uhal_message(self, hw = None, node =None, registerName=None, timeout=None, out_msg = True, w_r= "Read"):
        """Read incoming UHAL messages without storing any Queue
        node: obj: uhal._core type
        registerName: str:
        """
        reg_value = node.read()
        # Send IPbus transactions
        hw.dispatch()
        if out_msg:  self.logger.info(f'{w_r} {hex(reg_value.value())} : {registerName}')
        return reg_value

    def write_uhal_mopshub_message(self, hw =None, data=None,reg =None, timeout=None, out_msg= True):
        """Combining writing functions for different |CAN| interfaces
        Parameters
        ----------
        data : :obj:`list` of :obj:`int` or :obj:`bytes`
            Data bytes

        timeout : :obj:`int`, optional
            |SDO| write timeout in milliseconds. When :data:`None` or not
            given an infinit timeout is used.
        """
        nodes = []
        reqmsg = 0
        for r in reg:
            nodes = np.append(nodes,self.get_ual_node(hw =hw, registerName = r))
        [self.write_uhal_message(hw =hw,node =nodes[data.index(d)], data=d, registerName=r, timeout=timeout, out_msg=out_msg) for r,d in zip(reg,data)]
        reqmsg = 1
        return reqmsg

    def write_uhal_message(self,hw =None, node =None, data=None, registerName=None, timeout=None, out_msg = True ):
        reqmsg = 0
        node.write(data)
        reqmsg= 1
        reg_ret_value = self.read_uhal_message(hw = hw, node =node, registerName=registerName, timeout=timeout, out_msg = out_msg, w_r= "Writing")
        status = (hex(data) ==hex(reg_ret_value.value()))
        if out_msg and not status:  self.logger.warning(f'Writing mismatch in {registerName} [W: {hex(data)} |R:{hex(reg_ret_value.value())}]')
        # Send IPbus transactions
        hw.dispatch()
        #time.sleep(timeout)
        return reqmsg

    def build_response_sdo_msg(self, reg =[], out_msg = True):
        # Data_rec_reg is 76 bits = sdo[12bits]+payload[32bits]+bus_id[5bits]++3bits0+8bits0+16bits0
        reg_values = []
        data_ret = [0 for b in np.arange(9)]
        new_Bytes = [0 for b in np.arange(9)]
        responsereg = Analysis().binToHexa(bin(int(reg[0],16))[2:].zfill(32)
                                           +bin(int(reg[1],16))[2:].zfill(32)
                                           +bin(int(reg[2],16))[2:].zfill(32))
        for r in reg:
            try:
                reg_values = np.append(reg_values,hex(r))
            except:
                reg_values = np.append(reg_values,r)
        msg_bin_0 = bin(int(reg_values[0],16))[2:].zfill(32)
        msg_bin_1 = bin(int(reg_values[1],16))[2:].zfill(32)
        msg_bin_2 = bin(int(reg_values[2],16))[2:].zfill(32)
        data_ret  = [hex(Analysis().binToHexa(msg_bin_0[0:12]))#cobid
                   ,hex(Analysis().binToHexa(msg_bin_0[12:20]))
                   ,hex(Analysis().binToHexa(msg_bin_0[20:28]))
                   ,hex(Analysis().binToHexa(msg_bin_0[28:32]+msg_bin_1[0:4]))
                   ,hex(Analysis().binToHexa(msg_bin_1[4:12]))
                   ,hex(Analysis().binToHexa(msg_bin_1[12:20]) )
                   ,hex(Analysis().binToHexa(msg_bin_1[20:28]) )
                   ,hex(Analysis().binToHexa(msg_bin_1[28:32]+msg_bin_2[0:4]))
                   ,hex(Analysis().binToHexa(msg_bin_2[4:12]) )]
        new_Bytes= [data_ret[0],data_ret[1],data_ret[3],data_ret[2],data_ret[4],data_ret[8],data_ret[7],data_ret[6],data_ret[5]]

        for i in range(len(data_ret)):
            if new_Bytes[i] =='': new_Bytes[i]=0
        else:   pass
        return new_Bytes, responsereg

    def dumpMessage(self, cobid, msg, t):
        """Dumps a uhal message to the screen and log file
        Parameters
        ----------
        cobid : :obj:`int`
            |CAN| identifier
        msg : :obj:`bytes`
            |CAN| data - max length 8
        t : obj'int'
        """
        msgstr = '{:3X} {:d}   '.format(cobid, 8)
        for i in range(len(msg)):
            msgstr += '{:02x}  '.format(msg[i])
        msgstr += '    ' * (8 - len(msg))
        st = datetime.datetime.fromtimestamp(t).strftime('%H:%M:%S')
        msgstr += str(st)
        self.logger.info(msgstr)

    def enable_read_signal (self,timeout =None, out_msg = None):
         #wait for interrupt signal from FIFO
        hw = self.get_uhal_hardware()
        count, count_limit = 0, 2
        #irq_tra_sig = 0x0
        while (count !=count_limit):
            irq_tra_sig =   self.read_uhal_message(hw = hw,
                                                    node =self.get_ual_node(hw =hw, registerName = "reg3"),
                                                    registerName="reg3", timeout=timeout, out_msg = None)
            count= count+1
            if out_msg: self.logger.info(f'Read irq_tra_sig =  {irq_tra_sig} Count ({count})')
            time.sleep(timeout)
            if irq_tra_sig >=0x1:break
        #Read data  from FIFO
        if irq_tra_sig>0x0:
            found_msg =True
            if out_msg: self.logger.info(f'Found Message in the buffer (irq_tra_sig = {irq_tra_sig})')
            # Start read elink
            self.write_uhal_message(hw = hw,
                                         node =self.get_ual_node(hw =hw, registerName = "reg10"),
                                         registerName="reg10",
                                         data = 0x1,
                                         timeout=timeout, out_msg = False)
        else:
            found_msg = False
            self.logger.warning(f'Nothing Found in the buffer (irq_tra_sig = {irq_tra_sig})')
        return found_msg

    def read_uhal_mopshub_message(self, reg =None, timeout=None,  out_msg = True):
        hw = self.get_uhal_hardware()
        nodes = []
        reg_values = []
        respmsg = 0
        msg_found =  self.enable_read_signal(timeout= timeout, out_msg = out_msg)
        if msg_found:
            for r in reg:
                nodes = np.append(nodes,self.get_ual_node(hw =hw, registerName = r))
                reg_value = nodes[reg.index(r)].read()
                # Send IPbus transactions
                hw.dispatch()
                #time.sleep(timeout)#The code has really developed afer commenting this line
                if out_msg: self.logger.info(f'Read {r} Value = {hex(reg_value.value())}')
                reg_values = np.append(reg_values,hex(reg_value.value()))
            respmsg = 1
            t = time.time()
            data, responsereg =  self.build_response_sdo_msg(reg = reg_values, out_msg=out_msg)
            cobid = int(data[0],16)
            data_ret = [0 for b in np.arange(len(data)-1)]
            for i in np.arange(len(data_ret)): data_ret[i] = int(data[i+1],16)
            if out_msg: self.dumpMessage(cobid, data_ret, t)
            self.__uhalMsgQueue.appendleft((cobid, data_ret, t))
            return cobid, bytearray(data_ret), respmsg, hex(responsereg), t
        else:
            respmsg = 0
            self.__cnt["messageFailed_response"] =self.__cnt["messageFailed_response"]+ 1
            return None, None, respmsg, None, None

    def  return_valid_message(self, nodeId, index, subindex, cobid_ret, data_ret, SDO_TX, SDO_RX,timeout):
        messageValid = False
        status = 0
        respmsg, responsereg = 0, None
        messageValid_queue = False
        t0 = time.perf_counter()
        while time.perf_counter() - t0 < 1 and messageValid_queue == False:
                # check the message validity [nodid, msg size,...]
                for i, (cobid_ret, data_ret, t) in zip(range(len(self.__uhalMsgQueue)), self.__uhalMsgQueue):
                    messageValid_queue = (cobid_ret == SDO_RX + nodeId
                                    and data_ret[0] in [0x80, 0x43, 0x47, 0x4b, 0x4f, 0x42]
                                    and int.from_bytes([data_ret[1], data_ret[2]], 'little') == index
                                    and data_ret[3] == subindex)

                    if (messageValid_queue):
                        del self.__uhalMsgQueue[i]
                        break
                if (messageValid_queue ==False):
                    _, _, respmsg, responsereg, _ = self.read_uhal_mopshub_message(reg = ["reg0","reg1","reg2"], timeout=timeout, out_msg = None)
                self.__uhalMsgThread.join()
        # The following are the only expected response
        #
        # messageValid = (cobid_ret == SDO_RX + nodeId
        #                 and data_ret[0] in [0x80, 0x43, 0x47, 0x4b, 0x4f, 0x42]
        #                 and int.from_bytes([data_ret[1], data_ret[2]], 'little') == index
        #                 and data_ret[3] == subindex)
        if messageValid_queue:
            status = 1
            nDatabytes = 4 - ((data_ret[0] >> 2) & 0b11) if data_ret[0] != 0x42 else 4
            data = []
            for i in range(nDatabytes-1):
                data.append(data_ret[4 + i])
            return int.from_bytes(data, 'little'), messageValid_queue, status, respmsg, responsereg
        else:
            status = 0
            self.logger.info(f'SDO read response timeout (node {nodeId}, index'
                 f' {index:04X}:{subindex:02X})')
            self.__cnt["messageInvalid_queue"]=self.__cnt["messageInvalid_queue"]+1
            return None, messageValid_queue, status, respmsg, responsereg

    def read_adc(self,hw, bus_id,timeout):
        self.logger.debug(f'CIC Channel {bus_id} - ADC readout')

        adc_result = [[int(), int()] for _ in range(4)]
        adc_info = []
        self.logger.debug("Read ADC channels:")
        counter = 0
        for address in self.__address_byte:
            #adc_out = self.spi.xfer2([address, 0x00, 0x00, 0x00, 0x00])
            _, _, _, adc_out =  self.read_monitoring_uhal(hw =hw,
                                                              cobid = 0x20,
                                                              spi_reg =address,
                                                              spi_id=bus_id,
                                                              timeout=timeout,
                                                              out_msg =False)
            time.sleep(0.7)
            last_bits = bin(adc_out[4])[6:][:2]
            adc_info.append(adc_out)
            if adc_out[4] == 255:
                adc_result[int(last_bits, 2)][0] = self.__address_byte.index(address)
                adc_result[int(last_bits, 2)][1] = -1
            # search in the last four bits channel indicator bits
            elif last_bits in {'00', '01', '10'}:#indicates which physical inputs to be converted
                if bin(adc_out[4])[9:] == '1':
                    self.logger.warning(
                        f"OF-Error during ADC Readout of phy. channel {int(last_bits, 2)}")
                    self.cnt[f"OF-ERROR Channel {int(last_bits, 2)}"] += 1
                    self.logger.warning(adc_out[4])
                if bin(adc_out[4])[8:][:1] == '1':
                    self.logger.warning(
                        f"OD-Error during ADC Readout of phy. channel {int(last_bits, 2)}")
                    self.cnt[f"OD-ERROR Channel {int(last_bits, 2)}"] += 1
                    self.logger.warning(adc_out[4])
                try:#ch1 is Ucurr(in volt) has a apecial conversion
                    if last_bits == '01':
                        value = round(((adc_out[2] * 256 + adc_out[3]) * 0.03814697), 3)
                    else:
                        value = round(((adc_out[2] * 256 + adc_out[3]) * 0.03814697 / 1000), 3)
                    adc_result[int(last_bits, 2)][0] = int(last_bits, 2)
                    adc_result[int(last_bits, 2)][1] = value  # 2,5V Ref
                except ZeroDivisionError:
                    adc_result[int(last_bits, 2)][0] = int(last_bits, 2)
                    adc_result[int(last_bits, 2)][1] = -1
            elif last_bits == '11':
                if bin(adc_out[4])[9:] == '1':
                    self.logger.warning(
                        f"OF-Error during ADC Readout of phy. channel {int(last_bits, 2)}")
                    self.cnt[f"OF-ERROR Channel {int(last_bits, 2)}"] += 1
                    self.logger.warning(adc_out[4])
                if bin(adc_out[4])[8:][:1] == '1':
                    self.logger.warning(
                        f"OD-Error during ADC Readout of phy. channel {int(last_bits, 2)}")
                    self.cnt[f"OF-ERROR Channel {int(last_bits, 2)}"] += 1
                    self.logger.warning(adc_out[4])
                try:
                    v_ntc = round(((adc_out[2] * 256 + adc_out[3]) * 0.03814697 / 1000), 3)
                    r_ntc = v_ntc * (20 / 2.5)
                    value = round((298.15 / (1 - (298.15 / 3435) * np.log(10 / r_ntc))) - 273.15, 3)
                    adc_result[int(last_bits, 2)][0] = int(last_bits, 2)
                    adc_result[int(last_bits, 2)][1] = value
                except ZeroDivisionError:
                    adc_result[int(last_bits, 2)][0] = int(last_bits, 2)
                    adc_result[int(last_bits, 2)][1] = -1
            else:
                adc_result[self.__address_byte.index(address)][0] = self.__address_byte.index(address)
                adc_result[self.__address_byte.index(address)][1] = -1
                counter += 1
                self.cnt["error_cnt"] += 1
                if counter % 5 == 0:
                    self.cnt["bad_readout"] += 1
                    self.logger.warning(f"Bad readout - {adc_result} - {self.cnt}")

        if self.cnt["bad_readout"] % 3 == 1:
            self.cnt["reset_cnt"] += 1
            #self.cs5523_startup(spi_cs, bus_id, mp_id)
            self.logger.warning(f"Restart ADC on Bus {bus_id}")

        # print(f"ADC readout finished: Bus_id: {bus_id} - {adc_result}")
        self.logger.debug(f"ADC readout finished: Bus_id: {bus_id} - {adc_result}")
        return

    def read_monitoring_uhal(self,hw =None, spi_reg =None, spi_id=None,cobid = 0X20, timeout=1,out_msg=None):
        status =0;
        respmsg, responsereg  = 0, None
        #build Payload in a CAN SDO format
        mon_reg6_hex = Analysis().binToHexa(bin(cobid)[2:].zfill(8)+
                                            bin(spi_id)[2:].zfill(8)+
                                            bin(spi_reg)[2:].zfill(8)+
                                            bin(0)[2:].zfill(8))
        reqmsg =  self.write_uhal_mopshub_message(hw =hw,
                                              data=[mon_reg6_hex,0x0,0x0,0xa],
                                              reg = ["reg6","reg7","reg8","reg9"],
                                              timeout=timeout,
                                              out_msg = out_msg)
        #read the response from the socket
        _frame  =  self.read_uhal_mopshub_message(reg = ["reg0","reg1","reg2"],
                                                        timeout=timeout,
                                                        out_msg = out_msg)
        hw.dispatch()
        _, msg_ret,respmsg_ret, responsereg_ret, t = _frame
        if (not all(m is None for m in _frame[0:2])):
            responsereg_ret = bin(int(responsereg_ret,16))[2:].zfill(96)
            cobid_ret    = hex(Analysis().binToHexa(responsereg_ret[0:8]))
            spi_id_ret   = hex(Analysis().binToHexa(responsereg_ret[8:16]))
            spi_reg_ret  = hex(Analysis().binToHexa(responsereg_ret[16:24]))

            adc_out =   [hex(Analysis().binToHexa(responsereg_ret[24:32])),
                         hex(Analysis().binToHexa(responsereg_ret[32:40])),
                         hex(Analysis().binToHexa(responsereg_ret[40:48])),
                         hex(Analysis().binToHexa(responsereg_ret[48:56])),
                         hex(Analysis().binToHexa(responsereg_ret[56:64]))]
            xadc_code =  Analysis().binToHexa(responsereg_ret[64:76])
            temp_xadc = xadc_code*503.975/4096-273.15
            if out_msg: self.logger.info(f'cobid_ret:{cobid_ret}|| spi_id_ret: {spi_id_ret}||spi_reg_ret:{spi_reg_ret}||adc_out:{adc_out})')
            if out_msg: self.logger.info(f'FPGA temp_xadc:{round(temp_xadc,2)} C')
            adc_out =[int(adc_out[i],16) for i in range(len(adc_out))]
            last_bits = bin(adc_out[4])[2:][4:]
            print(hex(spi_reg),last_bits[1:3], adc_out, bin(adc_out[4])[2:])
            return cobid_ret, spi_id_ret, spi_reg_ret, adc_out
        else:
            status = 0
        #     if responsereg is not None: return None, reqmsg, hex(responsereg),respmsg, responsereg, status
            return None, None, None, None
        #

    def read_sdo_uhal(self,hw= None, bus= None, nodeId=None, index=None, subindex=None, timeout=1, SDO_TX=0x600, SDO_RX=0x580,out_msg=None):
        """Read an object via |SDO|

        Currently expedited and segmented transfer is supported by this method.
        The function will writing the dictionary request from the master to the node then read the response from the node to the master
        The user has to decide how to decode the data.

        Parameters
        ----------
        nodeId : :obj:`int`
            The id from the node to read from
        index : :obj:`int`
            The Object Dictionary index to read from
        subindex : :obj:`int`
            |OD| Subindex. Defaults to zero for single value entries.
        timeout : :obj:`int`, optional
            |SDO| timeout in milliseconds

        Returns
        -------
        :obj:`list` of :obj:`int`
            The data if was successfully read
        :data:`None`
            In case of errors
        """
        status =0;
        respmsg, responsereg  = 0, None
        if nodeId is None or index is None or subindex is None:
            self.logger.warning('SDO read protocol cancelled before it could begin.')
            self.__cnt["SDO read total"] = self.__cnt["SDO read total"]+1
            return None, None, None,respmsg, responsereg , status
        hw =  self.get_uhal_hardware()
        #build Payload in a CAN SDO format
        reg6_hex, reg7_hex, reg8_hex, requestreg = self.build_request_sdo_msg(cobid = SDO_TX+nodeId, bus = bus,  index=index, subindex=subindex)

        #write the Request to the Socket
        try:
            reqmsg =  self.write_uhal_mopshub_message(hw =hw,
                                                  data=[reg6_hex,reg7_hex,reg8_hex,0xa],
                                                  reg = ["reg6","reg7","reg8","reg9"],
                                                  timeout=timeout,
                                                  out_msg = out_msg)
        except:
            reqmsg = 0
        #read the response from the socket
        _frame  =  self.read_uhal_mopshub_message(reg = ["reg0","reg1","reg2"],
                                                       timeout=timeout,
                                                       out_msg = out_msg)
        hw.dispatch()
        cobid_ret, msg_ret,respmsg_ret, responsereg_ret, t = _frame
        if (not all(m is None for m in _frame[0:2])):
           data_ret, messageValid, status,respmsg, responsereg  =  self.return_valid_message(nodeId=nodeId,
                                                                                index=index,
                                                                                subindex=subindex,
                                                                                cobid_ret=cobid_ret,
                                                                                data_ret=msg_ret,
                                                                                SDO_TX=SDO_TX, SDO_RX=SDO_RX,
                                                                                timeout=timeout)
           if responsereg is None:
               responsereg = responsereg_ret
               respmsg = respmsg_ret
           # Check command byte
           if msg_ret[0] == (0x80):
                status =0
                abort_code = int.from_bytes(msg_ret[4:], 'little')
                self.logger.error(f'Received SDO abort message while reading '
                                  f'object {index:04X}:{subindex:02X} of node '
                                  f'{nodeId} with abort code {abort_code:08X}')
                if requestreg is not None: return None, reqmsg, hex(requestreg),respmsg, responsereg, status
                else : return None, reqmsg, requestreg,respmsg, responsereg, status
           else:
                return data_ret , reqmsg, hex(requestreg), respmsg, responsereg  , status

        else:
            status = 0
            if responsereg is not None: return None, reqmsg, hex(responsereg),respmsg, responsereg, status
            else : return None, reqmsg, hex(requestreg),respmsg, responsereg, status

    def build_request_sdo_msg(self,bus = None, cobid = None, index=None, subindex=None,msg_0 =0x40):
        max_data_bytes = 8
        msg = [0 for i in range(max_data_bytes)]
        msg[0] = msg_0
        msg[1], msg[2] = index.to_bytes(2, 'little')
        msg[3] = subindex
        msg_bin_0 = bin(msg[0])[2:].zfill(8)
        msg_bin_1 = bin(msg[1])[2:].zfill(8)
        msg_bin_2 = bin(msg[2])[2:].zfill(8)
        msg_bin_3 = bin(msg[3])[2:].zfill(8)
        reg6_hex = Analysis().binToHexa(bin(cobid)[2:].zfill(12)#12bits
                                        +msg_bin_0#8bits
                                        +msg_bin_2#8bits
                                        +msg_bin_1[0:4]#4bits
                                        )

        reg7_hex = Analysis().binToHexa(msg_bin_1[4:8]#4bits
                                        +msg_bin_3#8bits
                                        +bin(bus)[2:].zfill(8)#8bits
                                        +bin(0)[2:].zfill(8)#8bits
                                        +bin(0)[2:].zfill(4))#4bits

        reg8_hex = Analysis().binToHexa(bin(0)[2:].zfill(32))

        requestreg = Analysis().binToHexa(bin(cobid)[2:].zfill(12)#12bits
                                        +msg_bin_0#8bits
                                        +msg_bin_2#8bits
                                        +msg_bin_1#bin(0)[2:].zfill(4)#4bits
                                        #+bin(0)[2:].zfill(4)#4bits
                                        +msg_bin_3#8bits
                                        +bin(bus)[2:].zfill(8)#8bits
                                        +bin(0)[2:].zfill(8)#it was msg_bin_1 8bits
                                        +bin(0)[2:].zfill(4)
                                        +bin(0)[2:].zfill(32))
        return reg6_hex, reg7_hex, reg8_hex, requestreg

    def create_mopshub_adc_data_file(self,outputname, outputdir):
        # Write header to the data
        fieldnames = ['time',"test_tx",'bus_id',"nodeId","adc_ch","index","sub_index","adc_data", "adc_data_converted","reqmsg","requestreg","respmsg","responsereg", "status"]
        csv_writer = AnalysisUtils().build_data_base(fieldnames=fieldnames,outputname = outputname, directory = outputdir)
        return csv_writer

    def read_mopshub_adc_channels(self, hw, bus_range, file, directory,outputname, outputdir , nodeId, n_readings,timeout,csv_writer):
        """Start actual CANopen communication
        This function contains an endless loop in which it is looped over all
        ADC channels. Each value is read using
        :meth:`read_sdo_can_thread` and written to its corresponding
        """
        self.logger.info(f'Reading ADC channels of Mops with ID {nodeId}')
        dev = AnalysisUtils().open_yaml_file(file=file, directory=directory)
        # yaml file is needed to get the object dictionary items
        _adc_channels_reg = dev["adc_channels_reg"]["adc_channels"]
        _adc_index = list(dev["adc_channels_reg"]["adc_index"])[0]
        _channelItems = [int(channel) for channel in list(_adc_channels_reg)]
        # Write header to the data
        #fieldnames = ['time',"test_tx",'bus_id',"nodeId","adc_ch","index","sub_index","adc_data", "adc_data_converted","reqmsg","requestreg","respmsg","responsereg", "status"]
        #csv_writer = AnalysisUtils().build_data_base(fieldnames=fieldnames,outputname = outputname, directory = outputdir)
        monitoringTime = time.time()
        for point in np.arange(0, n_readings):
            for bus in bus_range:
                for node in nodeId:
                    # Read ADC channels
                    for c in tqdm(np.arange(len(_channelItems)),colour="green"):
                        channel =  _channelItems[c]
                        subindex = channel - 2
                        data_point, reqmsg, requestreg, respmsg,responsereg , status =  self.read_sdo_uhal(hw =hw,
                                                                                bus = bus,
                                                                                nodeId= node,
                                                                                index = int(_adc_index, 16),
                                                                                subindex = subindex,
                                                                                timeout = timeout,
                                                                                out_msg = False)

                        #time.sleep(0.01) #It makes no difference
                        ts = time.time()
                        elapsedtime = ts - monitoringTime
                        if data_point is not None:
                            adc_converted = Analysis().adc_conversion(_adc_channels_reg[str(channel)], data_point)
                            adc_converted = round(adc_converted, 3)
                            self.logger.info(f'[{point}] Got data for channel {channel} [{hex(subindex)}]: = {adc_converted}')
                        else:
                            adc_converted = None
                        csv_writer.writerow((str(elapsedtime),
                                             str(1),
                                             str(bus),
                                             str(node),
                                             str(channel),
                                             str(_adc_index),
                                             str(subindex),
                                             str(data_point),
                                             str(adc_converted),
                                             str(reqmsg),
                                             str(requestreg),
                                             str(respmsg),
                                             str(responsereg),
                                             status))

        self.logger.info(f'No. of invalid responses = {self.__cnt["messageInvalid_queue"]}|| No. of failed responses = {self.__cnt["messageFailed_response"]-1}')
        #self.logger.notice("ADC data are saved to %s/%s" % (outputdir,outputname))

    # Setter and getter functions
    def set_uhal_hardware(self, x):
        self.__hw = x

    def set_nodeList(self, x):
        self.__nodeList = x

    def set_channelPorts(self, x):
        self.__can_channels = x

    def set_channel(self, x):
        self.__channel = x

    def set_ipAddress(self, x):
        self.__ipAddress = x

    def set_bitrate(self, bitrate):
        if self.__interface == 'Kvaser':
            self.__bitrate = bitrate
        else:
            self.__bitrate = bitrate

    def set_sample_point(self, x):
        self.__sample_point = float(x)

    def get_DllVersion(self):
        ret = analib.wrapper.dllInfo()
        return ret

    def get_nodeList(self):
        return self.__nodeList

    def get_channelPorts(self):
        return self.__can_channels

    def get_bitrate(self):
        return self.__bitrate

    def get_sample_point(self):
        return self.__sample_point

    def get_ipAddress(self):
        """:obj:`str` : Network address of the AnaGate partner. Only used for
        AnaGate CAN interfaces."""
        if self.__interface == 'Kvaser':
            raise AttributeError('You are using a Kvaser CAN interface!')
        return self.__ipAddress

    def get_uhal_hardware(self):
        """:obj:`str` : Vendor of the CAN interface. Possible values are
        ``'Kvaser'`` and ``'AnaGate'``."""
        return self.__hw

    def get_channel(self):
        """:obj:`int` : Number of the crurrently used |CAN| channel."""
        return self.__channel

    def get_channelState(self, channel):
        return channel.state

    def __enter__(self):
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        if exception_type is KeyboardInterrupt:
            self.logger.warning('Received Ctrl+C event (KeyboardInterrupt).')
        else:
            self.logger.exception(exception_value)
        self.stop()
        logging.shutdown()
        return True

    @property
    def lock(self):
        """:class:`~threading.Lock` : Lock object for accessing the incoming
        message queue :attr:`canMsgQueue`"""
        return self.__lock

    @property
    def canMsgQueue(self):
        """:class:`collections.deque` : Queue object holding incoming |CAN|
        messages. This class supports thread-safe adding and removing of
        elements but not thread-safe iterating. Therefore the designated
        :class:`~threading.Lock` object :attr:`lock` should be acquired before
        accessing it.

        The queue is initialized with a maxmimum length of ``1000`` elements
        to avoid memory problems although it is not expected to grow at all.

        This special class is used instead of the :class:`queue.Queue` class
        because it is iterable and fast."""
        return self.__canMsgQueue

    @property
    def kvaserLock(self):
        """:class:`~threading.Lock` : Lock object which should be acquired for
        performing read or write operations on the Kvaser |CAN| channel. It
        turned out that bad things can happen if that is not done."""
        return self.__kvaserLock

    @property
    def cnt(self):
        """:class:`~collections.Counter` : Counter holding information about
        quality of transmitting and receiving. Its contens are logged when the
        program ends."""
        return self.__cnt

    @property
    def pill2kill(self):
        """:class:`threading.Event` : Stop event for the message collecting
        method :meth:`read_can_message_thread`"""
        return self.__pill2kill

    # @property
    def channel(self):
        """Currently used |CAN| channel. The actual class depends on the used
        |CAN| interface."""
        return self.ch0

    @property
    def bitRate(self):
        """:obj:`int` : Currently used bit rate. When you try to change it
        :func:`stop` will be called before."""
        if self.__interface == 'Kvaser':
            return self.__bitrate
        else:
            return self.ch0.baudrate

    @bitRate.setter
    def bitRate(self, bitrate):
        if self.__interface == 'Kvaser':
            self.stop()
            self.__bitrate = bitrate
            self.start()
        else:
            self.ch0.baudrate = bitrate

def main():
    """Wrapper function for using the server as a command line tool

    The command line tool accepts arguments for configuring the server which
    are transferred to the :class:`CanWrapper` class.
    """

    # Parse arguments
    parser = ArgumentParser(description='CANMOPS Interpreter for MOPS chip',
                            epilog='For more information contact '
                            'ahmed.qamesh@cern.ch',
                            formatter_class=ArgumentDefaultsHelpFormatter)

    parser.set_defaults(interface='socketcan')
    # CAN interface
    CGroup = parser.add_argument_group('CAN interface')
    iGroup = CGroup.add_mutually_exclusive_group()
    iGroup.add_argument('-K', '--kvaser', action='store_const', const='Kvaser',
                        dest='interface',
                        help='Use Kvaser CAN interface (default). When no '
                        'Kvaser interface is found or connected a virtual '
                        'channel is used.')
    iGroup.add_argument('-A', '--anagate', action='store_const',
                        const='AnaGate', dest='interface',
                        help='Use AnaGate Ethernet CAN interface')

    iGroup.add_argument('-S', '--socketcan', action='store_const',
                        const='socketcan', dest='interface',
                        help='Use socketcan  interface')

    # CAN settings group
    cGroup = parser.add_argument_group('CAN settings')
    cGroup.add_argument('-c', '--channel', metavar='CHANNEL',
                        help='Number of CAN channel to use',
                        default=0)

    cGroup.add_argument('-i', '--ipaddress', metavar='IPADDRESS',
                        default='192.168.1.254', dest='ipAddress',
                        help='IP address of the AnaGate Ethernet CAN '
                        'interface')
    cGroup.add_argument('-b', '--bitrate', metavar='BITRATE',
                        default=125000,
                        help='CAN bitrate as integer in bit/s')

    cGroup.add_argument('-sp', '--samplePoint', metavar='SAMPLEPOINT',
                        default=0.5,
                        help='CAN sample point in decimal')

    cGroup.add_argument('-sjw', '--sjw', metavar='SJW',
                        default=4,
                        help='Synchronization Jump Width')

    cGroup.add_argument('-tseg1', '--tseg1', metavar='tseg1',
                        default=0,
                        help='Time Segment1')

    cGroup.add_argument('-tseg2', '--tseg2', metavar='tseg2',
                        default=0,
                        help='Time Segment2')

    cGroup.add_argument('-nodeid', '--nodeid', metavar='nodeid',
                        default=0,
                        help='Node Id of the MOPS chip under test')

    # Logging configuration
    lGroup = parser.add_argument_group('Logging settings')
    lGroup.add_argument('-cl', '--console_loglevel',
                        choices={'NOTSET', 'SPAM', 'DEBUG', 'VERBOSE', 'INFO',
                                 'NOTICE', 'SUCCESS', 'WARNING', 'ERROR',
                                 'CRITICAL'},
                        default='INFO',
                        help='Level of console logging')

    args = parser.parse_args()

    # Start the server
    wrapper = CanWrapper(**vars(args))

class ConsumerThread(Thread):
    def run(self):
        global queue
        while True:
            lock.acquire()
            if not queue:
                print ("Nothing in queue, but consumer will try to consume")
            num = queue.pop(0)
            print ("Consumed", num)
            lock.release()
            time.sleep(random.random())

if __name__ == "__main__":
    main()

    ProducerThread().start()
    ConsumerThread().start()


from datetime import datetime
from flask import render_template, session, redirect, url_for, request, abort, current_app, flash,make_response
from flask_login import current_user
from . import main
from .forms import PostForm, EditProfileForm,EditProfileAdminForm, CommentForm
from .. import db, photos
from ..models import User,Role,Post,Comment
from ..email import send_email
from ..decorators import admin_required, permission_required
from ..models import Permission
from flask_login import login_required

@main.route("/", methods=["GET","POST"])
def index():
    form = PostForm()
    page = request.args.get('page', 1, type=int)
    show_followed = False
    show_yours = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
        show_yours = bool(request.cookies.get('show_yours', ''))
    if show_followed:
        query = current_user.followed_posts
    elif show_yours:
        query = Post.query.filter_by(author=current_user)
    else:
        query = Post.query
    pagination = query.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False)
    posts = pagination.items
    return render_template('index.html', form=form, posts=posts,show_followed=show_followed, pagination=pagination,show_yours=show_yours)

@main.route('/admin', methods=["GET","POST"])
@login_required
@admin_required
def for_admins_only():
    return "For administrators!"

@main.route('/moderator')
@login_required
@permission_required(Permission.MODERATE_COMMENTS)
def for_moderators_only():
    return "For comment moderators!"

@main.route("/user/<username>",methods=["GET","POST"])
def user(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        abort(404)
    page = request.args.get("page",1,type=int)
    pagination = user.posts.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],error_out=False)
    posts = pagination.items
    return render_template("user.html", user=user, posts=posts,pagination=pagination)

@main.route("/editProfile",methods=["GET","POST"])
@login_required
def edit_user():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.location = form.location.data
        current_user.about_me = form.about_me.data
        if form.photo.data:
            current_user.image_filename = photos.save(form.photo.data,name="user/" + current_user.username + ".")
            current_user.image_url = photos.url(current_user.image_filename)
        db.session.add(current_user)
        return redirect(url_for("main.user",username=current_user.username))
    form.location.data=current_user.location
    form.about_me.data=current_user.about_me
    return render_template("editProfile.html", form=form, image_url=current_user.image_url)

@main.route('/edit-profile/<int:id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_profile_admin(id):
    user = User.query.get_or_404(id)
    form = EditProfileAdminForm(user=user)
    if form.validate_on_submit():
        user.email = form.email.data
        user.username = form.username.data
        user.confirmed = form.confirmed.data
        user.role = Role.query.get(form.role.data)
        user.location = form.location.data
        user.about_me = form.about_me.data
        if form.photo.data:
            user.image_filename = photos.save(form.photo.data, name="user/" + user.username+".")
            user.image_url = photos.url(user.image_filename)
        db.session.add(user)
        return redirect(url_for('.user', username=user.username))
    form.email.data = user.email
    form.username.data = user.username
    form.confirmed.data = user.confirmed
    form.role.data = user.role_id
    form.location.data = user.location
    form.about_me.data = user.about_me
    return render_template('editProfile.html', form=form, user=user,image_url=user.image_url)

@main.route("/post/<int:id>",methods=['GET', 'POST'])
def post(id):
    show_more = False
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if current_user.can(Permission.COMMENT) and form.validate_on_submit():
        comment = Comment(body=form.body.data,author=current_user._get_current_object(),post=post)
        db.session.add(comment)
        return redirect(url_for('main.post',id=id))
    page = request.args.get('page', 1, type=int)
    pagination = Comment.query.filter_by(post_id=id,disable=False).order_by(Comment.timestamp.desc()).paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False)
    comments = pagination.items
    return render_template("post.html", form=form,posts=[post],comments=comments,pagination=pagination,show_more=show_more)

@main.route("/createPost", methods=["GET","POST"])
@login_required
def create_post():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
        post = Post(title=form.title.data,body=form.body.data,author=current_user._get_current_object())
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('main.post',id=post.id))
    return render_template("editPost.html",form=form,createPostFlag=True)

@main.route("/editPost/<int:id>", methods=['GET', 'POST'])
@login_required
def edit_post(id):
    post = Post.query.get_or_404(id)
    if current_user != post.author and not current_user.can(Permission.ADMINISTER):
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post.body = form.body.data
        post.title = form.title.data
        db.session.add(post)
        return redirect(url_for("main.post",id=post.id))
    form.body.data = post.body
    form.title.data = post.title
    return render_template("editPost.html",form=form)

@main.route('/follow/<username>')
@login_required
@permission_required(Permission.FOLLOW)
def follow(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('main.index'))
    if current_user.is_following(user):
        flash('You are already following this user.')
        return redirect(url_for('main.user', username=username))
    current_user.follow(user)
    return redirect(url_for('main.user', username=username))

@main.route('/unfollow/<username>')
@login_required
@permission_required(Permission.FOLLOW)
def unfollow(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('.index'))
    if not current_user.is_following(user):
        flash('You are not following this user.')
        return redirect(url_for('.user', username=username))
    current_user.unfollow(user)
    return redirect(url_for('.user', username=username))

@main.route('/followers/<username>')
def followers(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    pagination = user.followers.paginate(
        page, per_page=current_app.config['FLASKY_FOLLOWERS_PER_PAGE'],
        error_out=False)
    follows = [{'user': item.follower, 'timestamp': item.timestamp}
               for item in pagination.items]
    return render_template('followers.html', user=user, title="Followers of",
                           endpoint='.followers', pagination=pagination,
                           follows=follows)

@main.route('/followed-by/<username>')
def followed_by(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    pagination = user.followed.paginate(
        page, per_page=current_app.config['FLASKY_FOLLOWERS_PER_PAGE'],
        error_out=False)
    follows = [{'user': item.followed, 'timestamp': item.timestamp}
               for item in pagination.items]
    return render_template('followers.html', user=user, title="Followed by",
                           endpoint='.followed_by', pagination=pagination,
                           follows=follows)

@main.route('/all')
@login_required
def show_all():
    resp = make_response(redirect(url_for('.index')))
    resp.set_cookie('show_followed', '', max_age=30*24*60*60)
    resp.set_cookie('show_yours', '', max_age=30*24*60*60)

    return resp

@main.route('/yours')
@login_required
def show_yours():
    resp = make_response(redirect(url_for('.index')))
    resp.set_cookie('show_yours', '1', max_age=30*24*60*60)
    resp.set_cookie('show_followed', '', max_age=30*24*60*60)
    return resp

@main.route('/followed')
@login_required
def show_followed():
    resp = make_response(redirect(url_for('.index')))
    resp.set_cookie('show_followed', '1', max_age=30*24*60*60)
    resp.set_cookie('show_yours', '', max_age=30*24*60*60)
    return resp

@main.route("/moderate-comments", methods=["GET","POST"])
@permission_required(Permission.MODERATE_COMMENTS)
@login_required
def moderate_comments():
    page = request.args.get('page', 1, type=int)
    pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False)
    comments = pagination.items
    return render_template('comments.html', pagination=pagination,comments=comments)

@main.route("/disable-comment/<int:id>", methods=["GET","POST"])
@permission_required(Permission.MODERATE_COMMENTS)
@login_required
def disable_comment(id):
    comment = Comment.query.get_or_404(id)
    comment.disable = True
    db.session.add(comment)
    return redirect(url_for("main.moderate_comments", page=request.args.get('page', 1, type=int)))

@main.route("/enable-comment/<int:id>", methods=["GET","POST"])
@permission_required(Permission.MODERATE_COMMENTS)
@login_required
def enable_comment(id):
    comment = Comment.query.get_or_404(id)
    comment.disable = False
    db.session.add(comment)
    return redirect(url_for("main.moderate_comments", page=request.args.get('page', 1, type=int)))


from dacutils.messagedefinition import FieldDefinition

MESSAGE_IDS = {
    "EEPROM_UPDATES": 1000  # Set to correct value later
}

def get_eeprom_updates_format():
    """
    Creates and returns a new eeprom update format - maintain memory independence of the format
    """

    update_format = [
        FieldDefinition("data", "value for the 1st 4 bytes/ 1st & 2nd EEPROM variables", "uint", 5, [0,0,0,0,0]),
        FieldDefinition("action", "desired action (0 = read, 1 = write, 2 = read responce, 3 = write responce)", "uchar", 1, 0),
        FieldDefinition("errorCode", "0 = no error, 1 = out of range, 2 = invalid data, 3 = write not available", "uchar", 1, 0),
        FieldDefinition("offset", "starting EEPROM offset", "ushort", 1, 0),
        FieldDefinition("size", "EEPROM access size", "ushort", 1, 0),
        FieldDefinition("align", "byte alignment", "ushort", 1, 0)
    ]
    return update_format


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.template import RequestContext
from django.views.decorators.csrf import ensure_csrf_cookie
from .models import GenericData, Data, BatteryStatus, BatteryHealth, BatteryLevel, BatteryTemperature, CPUTotal, CPUUser, CPUKernel, CPULoad1, CPULoad2, CPULoad3, CPUHog1New, CPUHog2New, CPUHog3New, CPUHog4New, CPUHog5New, MemInfoTotalRam, MemInfoFreeRam, MemInfoUsedRam
from rest_framework import viewsets
from .serializers import GenericDataSerializer, UserSerializer, GroupSerializer, DataSerializer
from .serializers import BatteryStatusSerializer, BatteryHealthSerializer, BatteryLevelSerializer, BatteryTemperatureSerializer,MultBatteryStatusSerializer
from django.contrib.auth.models import User, Group
import requests
from django.contrib.auth.decorators import login_required
from .forms import GenericDataForm
from django.utils import timezone
import json

from drf_multiple_model.views import MultipleModelAPIView
from rest_framework.decorators import api_view
from rest_framework import routers

from django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt
from rest_framework.mixins import CreateModelMixin
from rest_framework.renderers import JSONRenderer

from .serializers import CPUTotalSerializer, CPUUserSerializer, CPUKernelSerializer, CPULoad1Serializer, CPULoad2Serializer,CPULoad3Serializer, CPUHog1Serializer, CPUHog2Serializer, CPUHog3Serializer, CPUHog4Serializer, CPUHog5Serializer, MemInfoTotalRamSerializer, MemInfoFreeRamSerializer, MemInfoUsedRamSerializer
from .models import TestInfo
from .serializers import TestInfoSerializer
import datetime
import calendar
# Create your views here.
#@ensure_csrf_cookie
def index(request):
	if (request.method == "GET"):
		#data = request.GET.get('username')
	# 	try:
		lasthealth = BatteryHealth.objects.all()[BatteryHealth.objects.count()-1].value
		laststatus = BatteryStatus.objects.all()[BatteryStatus.objects.count()-1].value
		lastlevel = BatteryLevel.objects.all()[BatteryLevel.objects.count()-1].value
		lasttemperature = BatteryTemperature.objects.all()[BatteryTemperature.objects.count()-1].value
		lastcpu = CPUTotal.objects.all()[CPUTotal.objects.count()-1].value
		lastram = MemInfoFreeRam.objects.all()[MemInfoFreeRam.objects.count()-1].value

		allbatterylevel = BatteryLevel.objects.all()

		date_from = datetime.datetime.now() - datetime.timedelta(days=1)
		bleveldatas = BatteryLevel.objects.filter(time__gte=date_from)

		info = {}
		contentLevel = []
		for data in bleveldatas:
			info = {
				"time" : str(data.time),
				"value" : data.value
			}
			contentLevel.append(info)

		date_from = datetime.datetime.now() - datetime.timedelta(days=1)
		btempdatas = BatteryTemperature.objects.filter(time__gte=date_from)

		info = {}
		contentTemp = []
		for data in btempdatas:
			info = {
				"time" : str(data.time),
				"value" : data.value/10
			}
			contentTemp.append(info)

		#for battery_level in allbatterylevel:

	# #return render(request, 'index.html', data)''

	# 		return (HttpResponse("last field:" + last['field']))
	# 		#return HttpResponse(json.dumps(last))
	# 	except:
	# 		return HttpResponse("Hello! You're at the Android Diagnosis index. No data to show yet or Exception happened.")
		return render(request, 'battery.html', {'lasthealth':lasthealth, 'laststatus':laststatus, 'lastlevel':lastlevel,'lasttemperature':lasttemperature/10,'lastcpu':lastcpu, 'lastram':lastram/1000, 'allbatterylevel':allbatterylevel, 'contentLevel':contentLevel, 'contentTemp':contentTemp})
	else:
	    return HttpResponse("Hello! You're at the Android Diagnosis index. Not allowed action.")
	   # context = {'foo': 'bar'}
	    #return render(request, 'index.html', context)

def indexcpu(request):
	if (request.method == "GET"):
		lasthealth = BatteryHealth.objects.all()[BatteryHealth.objects.count()-1].value
		laststatus = BatteryStatus.objects.all()[BatteryStatus.objects.count()-1].value
		lastlevel = BatteryLevel.objects.all()[BatteryLevel.objects.count()-1].value
		lasttemperature = BatteryTemperature.objects.all()[BatteryTemperature.objects.count()-1].value
		lastcpu = CPUTotal.objects.all()[CPUTotal.objects.count()-1].value

		lastcpuhog1 = CPUHog1New.objects.all()[CPUHog1New.objects.count()-1]
		lastcpuhog2 = CPUHog2New.objects.all()[CPUHog2New.objects.count()-1]
		lastcpuhog3 = CPUHog3New.objects.all()[CPUHog3New.objects.count()-1]
		lastcpuhog4 = CPUHog4New.objects.all()[CPUHog4New.objects.count()-1]
		lastcpuhog5 = CPUHog5New.objects.all()[CPUHog5New.objects.count()-1]

		lastramfree = MemInfoFreeRam.objects.all()[MemInfoFreeRam.objects.count()-1].value
		lastramtotal = MemInfoTotalRam.objects.all()[MemInfoTotalRam.objects.count()-1].value
		lastramused = MemInfoUsedRam.objects.all()[MemInfoUsedRam.objects.count()-1].value

		ramfree_percent = round((lastramfree/float(lastramtotal))*100, 2)
		ramused_percent = round((lastramused/float(lastramtotal))*100, 2)

		lastload1 = CPULoad1.objects.all()[CPULoad1.objects.count()-1].value
		lastload2 = CPULoad2.objects.all()[CPULoad2.objects.count()-1].value
		lastload3 = CPULoad3.objects.all()[CPULoad3.objects.count()-1].value

		date_from = datetime.datetime.now() - datetime.timedelta(days=1)
		cpudatas = CPUTotal.objects.filter(time__gte=date_from)
		countcpu = CPUTotal.objects.filter(time__gte=date_from).count

		info = {}
		content = []
		for data in cpudatas:
			info = {
				"time" : str(data.time),
				"value" : data.value
			}
			content.append(info)

# created_documents = CreatedDocumentDetails.objects.filter(
#      user=user, created_document_timestamp__gte=date_from).count()

		return render(request, 'cpu.html',{'lasthealth':lasthealth, 'laststatus':laststatus, 'lastlevel':lastlevel,'lasttemperature':lasttemperature/10,'lastcpu':lastcpu, 'lastram':lastramfree/1000, 'cpuhog1':lastcpuhog1, 'cpuhog2':lastcpuhog2, 'cpuhog3':lastcpuhog3, 'cpuhog4':lastcpuhog4, 'cpuhog5':lastcpuhog5, 'lastramfree':lastramfree, 'lastramused':lastramused, 'lastramtotal':lastramtotal, 'ramfree_percent':ramfree_percent, 'ramused_percent':ramused_percent, 'lastload1':lastload1, 'lastload2':lastload2, 'lastload3':lastload3, 'cpudatas':content, 'countcpu':countcpu})
	else:
	    return HttpResponse("Hello! You're at the Android Diagnosis index. Not allowed action.")

def indexremotetest(request):
	if (request.method == "GET"):
		query = TestInfo.objects.all().order_by('-id')
		return render(request, 'remote_testing.html',{"query":query})
	else:
	    return HttpResponse("Hello! You're at the Android Diagnosis index. Not allowed action.")

def indexproject(request):
	if (request.method == "GET"):
		return render(request, 'project_details.html')
	else:
	    return HttpResponse("Hello! You're at the Android Diagnosis index. Not allowed action.")

def indexreport(request):
	if (request.method == "GET"):
		return render(request, 'report.html')
	else:
	    return HttpResponse("Hello! You're at the Android Diagnosis index. Not allowed action.")

def indexcontacts(request):
	if (request.method == "GET"):
		return render(request, 'contacts.html')
	else:
	    return HttpResponse("Hello! You're at the Android Diagnosis index. Not allowed action.")

def gettestinfo(request):
	if request.method == "GET":
		test = TestInfo.objects.filter(status="Pending").first()
		try:
			myresponse = {"id": test.idnum , "name" : test.name }
			return HttpResponse(json.dumps(myresponse))

		except Exception:
			myresponse = {"id": -1, "name": "not pending"}
			return HttpResponse(json.dumps(myresponse))

	else:
		return HttpResponse("action not allowed.")

@csrf_exempt
@api_view(['POST'])
def posttestinfo(request):
	if request.method == "POST":
		data = request.data
		test = TestInfo.objects.filter(idnum=data["id"]).first()
		test.status = data["status"]
		test.message = data["message"]
		test.save(update_fields=["status","message"])
		return HttpResponse(test.message)
	else:
		return HttpResponse("not allowed action")

##UPLOAD BATTERY TEST buna cevir test name i

def runbattery(request):
	if request.method == "GET":
		test = TestInfo.objects.create(idnum=TestInfo.objects.count()+1, name = "Upload Battery Test", status = "Pending", message="...")
		test.save()
		return HttpResponseRedirect("..")

def runbatterystatus(request):
	if request.method == "GET":
		test = TestInfo.objects.create(idnum=TestInfo.objects.count()+1, name = "Battery Status", status = "Pending", message="...")
		test.save()
		return HttpResponseRedirect("..")

def runbluetooth(request):
	if request.method == "GET":
		test = TestInfo.objects.create(idnum=TestInfo.objects.count()+1, name = "Bluetooth", status = "Pending", message="...")
		test.save()
		return HttpResponseRedirect("..")

def runspeed(request):
	if request.method == "GET":
		test = TestInfo.objects.create(idnum=TestInfo.objects.count()+1, name = "Speed", status = "Pending", message="...")
		test.save()
		return HttpResponseRedirect("..")

#@ensure_csrf_cookie
@csrf_exempt
@api_view(['POST'])
def postdata(request):
	if (request.method == "POST"):

		#return HttpResponse(request.POST.getlist('battery_status')[0])
		try:
			listOfThings = request.data['battery_status']
			mylist = json.loads(listOfThings)
			serialized = BatteryStatusSerializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['battery_level']
			mylist = json.loads(listOfThings)
			serialized = BatteryLevelSerializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['battery_temperature']
			mylist = json.loads(listOfThings)
			serialized = BatteryTemperatureSerializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['battery_health']
			mylist = json.loads(listOfThings)
			serialized = BatteryHealthSerializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()
				#jsondata = JSONRenderer().render(serialized.data)

			listOfThings = request.data['cpu_total']
			mylist = json.loads(listOfThings)
			serialized = CPUTotalSerializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()
#deletedcpukernel
			# listOfThings = request.data['cpu_kernel']
			# mylist = json.loads(listOfThings)
			# serialized = CPUKernelSerializer(data=mylist, many=True)
			# if serialized.is_valid():
			# 	serialized.save()
#deletecpuuser
			# listOfThings = request.data['cpu_user']
			# mylist = json.loads(listOfThings)
			# serialized = CPUUserSerializer(data=mylist, many=True)
			# if serialized.is_valid():
			# 	serialized.save()

			listOfThings = request.data['cpu_load1']
			mylist = json.loads(listOfThings)
			serialized = CPULoad1Serializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['cpu_load2']
			mylist = json.loads(listOfThings)
			serialized = CPULoad2Serializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['cpu_load3']
			mylist = json.loads(listOfThings)
			serialized = CPULoad3Serializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['cpu_hog1']
			mylist = json.loads(listOfThings)
			serialized = CPUHog1Serializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['cpu_hog2']
			mylist = json.loads(listOfThings)
			serialized = CPUHog2Serializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['cpu_hog3']
			mylist = json.loads(listOfThings)
			serialized = CPUHog3Serializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['cpu_hog4']
			mylist = json.loads(listOfThings)
			serialized = CPUHog4Serializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['cpu_hog5']
			mylist = json.loads(listOfThings)
			serialized = CPUHog5Serializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['ram_total']
			mylist = json.loads(listOfThings)
			serialized = MemInfoTotalRamSerializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['ram_free']
			mylist = json.loads(listOfThings)
			serialized = MemInfoFreeRamSerializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

			listOfThings = request.data['ram_used']
			mylist = json.loads(listOfThings)
			serialized = MemInfoUsedRamSerializer(data=mylist, many=True)
			if serialized.is_valid():
				serialized.save()

				return HttpResponse(('created'), status=201)

		except:
				return HttpResponse('notcreated', status=500)
		#jsond = json.dumps(request.POST.getlist('tracks'))
		return HttpResponse('notcreated', status=400)

		#data = request.GET.get('username')
		#return HttpResponse(request.POST.get('jsondata'))
		#generic = GenericData.objects.create(jsondata =request.POST.get('jsondata'))
		#statusdatas = json.loads(request.POST.get('batterystatus'))
		# healthdatas = request.POST['batterystatus'].getList("value")
		# for healthdata in healthdatas:
		# 	print (healthdata)

		# return HttpResponse(healthdatas)
	# 	form = GenericDataForm(request.POST)
	# #return render(request, 'index.html', data)
	# 	if form.is_valid:
	# 		generic = GenericData.objects.create(jsondata =request.POST.get('jsondata'))
	# 		return HttpResponse(generic.jsondata)
	# 	else:
	# 		return HttpResponse('not valid form')
	# else:
	# 	form = GenericDataForm()
	# return render(request, 'index.html', {'form': form})
	else:
		return HttpResponse("This api is only for POST", status=400)

# class CreateListModelMixin(object):

# 	def get_serializer(self, *args, **kwargs):
# 		if isinstance(kwargs.get('data',{}),list):
# 			kwargs['many'] = True
# 		return super(self).get_serializer(*args,**kwargs)

class BatteryStatusViewSet(viewsets.ModelViewSet):

	queryset = BatteryStatus.objects.all()
	serializer_class= BatteryStatusSerializer

	# def get_serializer(self, instance=None, data=None, many=False, partial=False):
	# 	return super(BatteryStatusViewSet,self).get_serializer(instance=instance, data=data, many=True, partial=partial)

	# def get_serializer(self, *args, **kwargs):
	# 	if isinstance(kwargs.get('data',{}),list):
	# 		kwargs['many'] = True
	# 	return super(CreateListModelMixin,self).get_serializer(*args,**kwargs)

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['battery_status']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

	# def create(self, request, *args, **kwargs):
	# 	serializer = self.get_serializer(data=request.data, many=True)
	# 	serializer.is_valid(raise_exception=True)
	# 	for batterystatus_data in serializer.validated_data:
	# 	    obj = BatteryStatus.objects.create(time= batterystatus_data['time'], value = batterystatus_data['value'])
	# 	    obj.save()
	# 	    return HttpResponse("hey")

	# 	return HttpResponse(serializer)

class TestInfoViewSet(viewsets.ModelViewSet):
	queryset = TestInfo.objects.all()
	serializer_class = TestInfoSerializer

class BatteryHealthViewSet(viewsets.ModelViewSet):

	queryset = BatteryHealth.objects.all()
	serializer_class= BatteryHealthSerializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['battery_health']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class BatteryLevelViewSet(viewsets.ModelViewSet):

	queryset = BatteryLevel.objects.all()
	serializer_class= BatteryLevelSerializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['battery_level']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class BatteryTemperatureViewSet(viewsets.ModelViewSet):

	queryset = BatteryTemperature.objects.all()
	serializer_class= BatteryTemperatureSerializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['battery_temperature']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPUTotalViewSet(viewsets.ModelViewSet):

	queryset = CPUTotal.objects.all()
	serializer_class= CPUTotalSerializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_total']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPUUserViewSet(viewsets.ModelViewSet):

	queryset = CPUUser.objects.all()
	serializer_class= CPUUserSerializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_user']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPUKernelViewSet(viewsets.ModelViewSet):

	queryset = CPUKernel.objects.all()
	serializer_class= CPUKernelSerializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_kernel']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPULoad1ViewSet(viewsets.ModelViewSet):

	queryset = CPULoad1.objects.all()
	serializer_class= CPULoad1Serializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_load1']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPULoad2ViewSet(viewsets.ModelViewSet):

	queryset = CPULoad2.objects.all()
	serializer_class= CPULoad2Serializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_load2']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPULoad3ViewSet(viewsets.ModelViewSet):

	queryset = CPULoad3.objects.all()
	serializer_class= CPULoad3Serializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_load3']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPUHog1ViewSet(viewsets.ModelViewSet):

	queryset = CPUHog1New.objects.all()
	serializer_class= CPUHog1Serializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_hog1']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPUHog2ViewSet(viewsets.ModelViewSet):

	queryset = CPUHog2New.objects.all()
	serializer_class= CPUHog2Serializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_hog2']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPUHog3ViewSet(viewsets.ModelViewSet):

	queryset = CPUHog3New.objects.all()
	serializer_class= CPUHog3Serializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_hog3']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPUHog4ViewSet(viewsets.ModelViewSet):

	queryset = CPUHog4New.objects.all()
	serializer_class= CPUHog4Serializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_hog4']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class CPUHog5ViewSet(viewsets.ModelViewSet):

	queryset = CPUHog5New.objects.all()
	serializer_class= CPUHog5Serializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['cpu_hog5']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class MemInfoTotalRamViewSet(viewsets.ModelViewSet):

	queryset = MemInfoTotalRam.objects.all()
	serializer_class= MemInfoTotalRamSerializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['meminfo_totalram']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class MemInfoFreeRamViewSet(viewsets.ModelViewSet):

	queryset = MemInfoFreeRam.objects.all()
	serializer_class= MemInfoFreeRamSerializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['meminfo_freeram']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class MemInfoUsedRamViewSet(viewsets.ModelViewSet):

	queryset = MemInfoUsedRam.objects.all()
	serializer_class= MemInfoUsedRamSerializer

	def create(self, request, *args, **kwargs):
		try:
			listOfThings = request.data['meminfo_usedram']
			mylist = json.loads(listOfThings)
			print(listOfThings)
			serializer = self.get_serializer(data=mylist, many= True)
		except KeyError:
			mylist = request.data
			serializer = self.get_serializer(data=mylist)

		if serializer.is_valid():
			serializer.save()
			return HttpResponse("created",status=201)

		return HttpResponse(request.data,status=404)

class DataViewSet(viewsets.ModelViewSet):

	queryset = Data.objects.all()
	serializer_class= DataSerializer

class GenericDataViewSet(viewsets.ModelViewSet):

	queryset = GenericData.objects.all()
	serializer_class= GenericDataSerializer

	def create(self, request, *args, **kwargs):
		serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list))
		serializer.is_valid(raise_exception=True)
		self.perform_create(serializer)
		headers = self.get_success_headers(serializer.data)
		#return HttpResponse(serializer.data, status=status.HTTP_201_CREATED,headers=headers)
		return HttpResponse("created")

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer

class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


import xmind
from cmp_command_processor.src.controllers.interfaces.BaseCommandProcessor import BaseCommandProcessor
from cmp_command_processor.src.controllers.interfaces.ResponseContainer import ResponseContainer

class SheetCommandsProcessor(BaseCommandProcessor):
    """Sheet commands"""

    def __init__(self, **kwargs):
        super(SheetCommandsProcessor, self).__init__()

    def create(self, user_id: str, title: str) -> bool:
        try:
            _xmind_workbook, _current_file = self.get_workbook(user_id)
            _new_sheet = _xmind_workbook.createSheet()
            _new_sheet.setTitle(title)
            _xmind_workbook.addSheet(_new_sheet)
            xmind.save(_xmind_workbook, self.get_full_file_path(user_id, \
                _current_file))
            return True
        except:
            return False

    def select(self, user_id: str, virtual_index: int) -> bool:
        try:
            _xmind_workbook, _current_file = self.get_workbook(user_id)
            _sheets = [sheet.getTitle() for sheet in _xmind_workbook.getSheets()]
            _response_container = ResponseContainer(_sheets)
            _sheet_to_use = \
                _response_container.get_title_by_index(virtual_index)
            _old_index = _sheets.index(_sheet_to_use)
            _xmind_workbook.moveSheet(_old_index, 0)
            xmind.save(_xmind_workbook, self.get_full_file_path(user_id, \
                _current_file))
            return True
        except:
            return False

    def list(self, user_id: str) -> ResponseContainer:
        _xmind_workbook, _ = self.get_workbook(user_id)
        _sheets = [sheet.getTitle() for sheet in _xmind_workbook.getSheets()]
        _response_container = ResponseContainer(_sheets)
        return _response_container

    def delete(self, user_id: str, virtual_index: int) -> bool:
        try:
            _xmind_workbook, _current_file = self.get_workbook(user_id)
            _sheets = [sheet.getTitle() for sheet in _xmind_workbook.getSheets()]
            _response_container = ResponseContainer(_sheets)
            _sheet_to_use = \
                _response_container.get_title_by_index(virtual_index)
            _old_index = _sheets.index(_sheet_to_use)
            _xmind_workbook.removeSheet(_xmind_workbook.getSheets()[_old_index])
            xmind.save(_xmind_workbook, self.get_full_file_path(user_id, \
                _current_file))
            return True
        except:
            return False

    def current(self, user_id: str) -> str:
        try:
            _xmind_workbook, _ = self.get_workbook(user_id)
            return _xmind_workbook.getPrimarySheet().getTitle()
        except:
            return None

    def get_workbook(self, user_id: str) -> \
        (xmind.core.workbook.WorkbookDocument, str):
        _, _meta_json = self.read_meta_file(user_id)
        _current_file = _meta_json.current_file.file_name
        _xmind_workbook = xmind.load(self.get_full_file_path(user_id, \
                _current_file))
        return _xmind_workbook, _current_file