Ejemplo n.º 1
0
def Client():
    id = str(uuid.uuid4())
    data_toPrint = "ClientThread: Client Thread Running ..."
    #print (data_toPrint)
    while True:
        Feeder.feeder(id,data_toPrint)
        data_toPrint = ""
        if Serial.MessageFromSerial != "":
            ClientSocket = socket(AF_INET,SOCK_DGRAM)
            if Server.RemoteIP != "":
                ClientSocket.sendto(Serial.MessageFromSerial.encode(),(Server.RemoteIP,10000))
                data_toPrint = Serial.MessageFromSerial.decode()
                # Remove last 3 chars (CR LF)
                data_toPrint = "CT: Sent to->[{}] Data->[{}]".format(Server.RemoteIP,data_toPrint[:-2])
                #print(data_toPrint)
            else:
                ClientSocket.setsockopt(SOL_SOCKET,SO_BROADCAST,1)
                ClientSocket.sendto(Serial.MessageFromSerial.encode(),('192.168.1.255',10000))
                data_toPrint = Serial.MessageFromSerial.decode()
                # Remove last 3 chars (CR LF)
                data_toPrint = "CT: Sent to->[192.168.1.255] Data->[{}]".format(data_toPrint[:-2])
                #print(data_toPrint)
            ClientSocket.close()
            Serial.MessageFromSerial = ""
            Server.RemoteIP = ""
Ejemplo n.º 2
0
def plot_distribution_with_threshhold(model, threshhold, n=1000):
    scores, imgs = Feeder.create_and_rate_n_images(model, n)
    highscores = [Feeder.get_highest_score_and_class(s) for s in scores]
    threshholded = [c for c, a in highscores if a > threshhold]
    plt.hist(x=threshholded, bins=43)
    plt.grid(axis='y', alpha=0.75)
    plt.xlabel('Label')
    plt.ylabel('Frequency')
    plt.title('Label Distribution')
    plt.show()
Ejemplo n.º 3
0
def plot_distribution_with_compared_threshhold(model, threshhold, n=1000):
    scores, imgs = Feeder.create_and_rate_n_images(model, n)
    topscorer = [Feeder.get_highest_score_and_class(s) for s in scores]
    threshholded = [c for c, a in topscorer if a > threshhold]
    unthreshholded = [c for c, a in topscorer]
    plt.figure()
    plt.hist([unthreshholded, threshholded], 43)
    plt.xlabel('Label')
    plt.ylabel('Frequency')
    plt.title('Label Distribution')
    plt.show()
Ejemplo n.º 4
0
def plot_prop_dist(model, n=1000):
    scores, imgs = Feeder.create_and_rate_n_images(model, n)
    topscorer = []
    for s in scores:
        c, a = Feeder.get_highest_score_and_class(s)
        topscorer.append(a)
    plt.hist(topscorer, bins=100, normed='density')
    plt.xlabel('Prop')
    plt.ylabel('Frequency')
    plt.title('Propability Distribution')
    plt.show()
Ejemplo n.º 5
0
def plot_prop_dist_of_label(model, label, n=1000):
    scores, imgs = Feeder.create_and_rate_n_images(model, n)
    labelScores = [s[label] for s in scores]
    plt.hist(labelScores, bins=20, normed='density')
    plt.xlabel('Prop')
    plt.ylabel('Frequency')
    plt.title('Propability Distribution')
    plt.show()
Ejemplo n.º 6
0
def plot_all_scores(model, n=1000):
    #Not Really Human Readable, but maybe Someone can improve?
    scores, imgs = Feeder.create_and_rate_n_images(model, n)
    plt.hist(scores, bins=5, density=True)
    plt.xlabel('Prop')
    plt.ylabel('Frequency')
    plt.title('Propability Distribution')
    plt.show()
Ejemplo n.º 7
0
def Tx():
    TxId = str(uuid.uuid4())
    data_toPrint = "TxST: Tx Thread Running ..."
    #print (data_toPrint)
    while True:
        Feeder.feeder(TxId,data_toPrint)
        data_toPrint = ""
        if Server.MessageFromUDP != "":
            try:
                port.write(Server.MessageFromUDP)
                # Remove last 3 chars (CR LF)
                data_toPrint = "TxST: Tx Data->[{}]".format(Server.MessageFromUDP[:-2])
                #print (data_toPrint)
                Server.MessageFromUDP = ""
            except serial.SerialException as e:
                data_toPrint = "TxST: Error->[{}]".format(e)
                #print (data_toPrint)
                port.flushOutput()
Ejemplo n.º 8
0
def Rx():
    RxId = str(uuid.uuid4())
    data_toPrint = "RxST: Rx Thread Running ..."
    #print (data_toPrint)
    while True:
        global MessageFromSerial
        Feeder.feeder(RxId,data_toPrint)
        try:
            MessageFromSerial = port.readline()
            # Remove last 3 chars (CR LF)
            data_toPrint = "RxST: Rx Data->[{}]".format(MessageFromSerial[:-2])
            #print (data_toPrint)
        except serial.SerialException as e:
            data_toPrint = "RxST: Error->[{}]".format(e)
            #print (data_toPrint)
            port.flushInput()
        except serial.SerialTimeoutException:
            data_toPrint = ""
Ejemplo n.º 9
0
def degenerate(model,
               image,
               label,
               alternationfn=_noise,
               iterations=10,
               decay=0.01,
               maxloops=2000,
               verbose=False,
               history=True):
    totalLoops = 0
    depth = 0
    lastScores, lastImage = Feeder.predict_single_image(model, image)
    lastLabelScore = lastScores[label]

    # To check if we put garbage in
    print("StartConfidence:", lastLabelScore)

    if history:
        h = []

    while (depth < iterations and totalLoops < maxloops):
        totalLoops += 1
        degenerated = alternationfn(lastImage.copy())
        degScores, degImage = Feeder.predict_single_image(model, degenerated)
        degLabelScore = degScores[label]

        if verbose:
            print("Score:", degLabelScore, "Depth:", depth, "Loop:",
                  totalLoops)
        if history:
            h.append((degLabelScore, depth))

        if (degLabelScore >= lastLabelScore - decay):
            lastImage = degImage
            lastLabelScore = degLabelScore
            depth += 1
    if h != []:
        plotHistory(h)
        return lastLabelScore, lastImage, h
    else:
        return lastLabelScore, lastImage
Ejemplo n.º 10
0
def Server ():
    global MessageFromUDP,RemoteIP

    id = str(uuid.uuid4())
    s = socket(AF_INET,SOCK_DGRAM)
    s.setblocking(False)
    s.bind(('',10000))
    # Find LocalIp from OS.
    ifconfig = os.popen("ifconfig").read()
    # Match LocalIp with Regular Expression
    IpMatch = re.search('\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}',ifconfig)
    # Assign Result
    localaddress = IpMatch.group()
    diagnosticMsg = "ST: Server Running on->[{}]:[{}]".format(localaddress,'10000')
    #print(diagnosticMsg)
    while True:
        Feeder.feeder(id,diagnosticMsg)
        try:
            data,address=s.recvfrom(256)
            data_toPrint = data.decode()
            # Remove last 3 chars (CR LF)
            data_toPrint = data_toPrint[:-2]
            RemoteIP,port = address
            # Find LocalIp from OS.
            ifconfig = os.popen("ifconfig").read()
            # Match LocalIp with Regular Expression
            IpMatch = re.search('\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}',ifconfig)
            # Assign Result
            localaddress = IpMatch.group()
            if localaddress != RemoteIP:
                diagnosticMsg = "ST: Cx Received: Address->[{}] Port->[{}] Data->[{}]"\
                    .format(RemoteIP,port,data_toPrint)
                #print (diagnosticMsg)
                MessageFromUDP = data.decode()
            else:
                diagnosticMsg = "ST: Cx Received: Address->[Mine!]: Echo do nothing!"
                #print (diagnosticMsg)
        except error:
            diagnosticMsg = ""
Ejemplo n.º 11
0
    def dialurl(self):
        newurl = simpledialog.askstring("More links",
                                        "Please Enter URL.",
                                        parent=self.launch)

        urlOK = False

        if newurl:
            if '/rss' in newurl or '.xml' in newurl or '.rss' in newurl:
                urlOK = Feeder.validlink(newurl)

            if urlOK:
                addtolist(newurl, self.URLlist)
                self.url.insert(tk.END, newurl)
            else:
                self.tkInvalid()
Ejemplo n.º 12
0
    def __init__(self, is_Training=False):
        self.is_Training = is_Training

        self.tf_Session = tf.Session()

        self.feeder = Feeder.Feeder(is_Training=is_Training)

        self.Tensor_Generate()

        self.tf_Saver = tf.train.Saver(
            var_list=[
                v for v in tf.all_variables()
                if not (v.name.startswith('speaker_embedding')
                        or v.name.startswith('mel_to_spectrogram'))
            ],
            max_to_keep=5,
        )

        self.Speaker_Embedding_Load()
        self.Vocoder_Load()
Ejemplo n.º 13
0
print('INITIAL SETTINGS FROM GUI:')
print(a.doCalendar + ' Calendar', a.foodToSearch, a.URLlist, sep='\n')

foods = a.foodToSearch

#Token gui for plotting map
token = gui.return_token()
mapbox_access_token = token

#calendar
foodEvents = []

#getting all the food events in the url list
for url in a.URLlist:
    print("Working on:", url)
    feeder = Feeder.main(url, foods)
    [foodEvents.append(Es) for Es in feeder.foodEs]
if len(foodEvents) == 0:
    print("didn't find anything :(")
else:
    print('\nOpening webpage')
    #Sorting food events
    Times = list(map(yeartime, foodEvents))
    temp = [[event, time] for event, time in zip(foodEvents, Times)]
    temp = sorted(temp, key=lambda x: x[1])
    foodEvents = [event[0] for event in temp]

    #Do Calendar if desired
    Feeder.doCalendar(foodEvents, a.doCalendar)

    #Plot events
Ejemplo n.º 14
0
def SendCommand():
    global tenSec, Rx, messageToSend, errorCounter, _38, _39, responseToServer

    serialId = str(uuid.uuid4())
    data_toPrint = "serialComs: serialComs Thread Running ..."

    logging.info("TxST: SendCommand Thread Running ...")

    port.flushOutput()

    waitingForConsoleCommand = False

    while True:
        # Feed Watchdog Server
        Feeder.feeder(serialId, data_toPrint)

        if apiClient.Command:
            command = apiClient.G4Command+"\x0D"
            waitingForConsoleCommand = True
            Rx = True
        elif messageToSend == 'Config':
            command = "00SZ50132\x0D"
            Rx = True
        elif messageToSend == 'MD0':
            command = "00MD0\x0D"
            Rx = True
        elif messageToSend == 'M1':
            command = "00M1\x0D"
            Rx = True
        elif messageToSend == 'M2':
            command = "00M2\x0D"
            Rx = True
        elif messageToSend == 'M3':
            command = "00M3\x0D"
            Rx = True
        elif messageToSend == 'M4':
            command = "00M4\x0D"
            Rx = True
        elif messageToSend == 'M5':
            command = "00M5\x0D"
            Rx = True
        elif messageToSend == 'M6':
            command = "00M6\x0D"
            Rx = True
        elif messageToSend == 'M7':
            command = "00M7\x0D"
            Rx = True
        elif messageToSend == 'M8':
            command = "00M8\x0D"
            Rx = True

        data_toPrint = command[:-1]
        logging.debug("[%s]TxST: Tx Data->[%s]".format(time.clock(), data_toPrint))
        port.write(command)
        while Rx:
            try:
                MessageFromSerial = port.readline()
                # Remove last 3 chars (CR LF)
                data_toPrint = MessageFromSerial[:-2]
                logging.debug("[%s]RxST: Rx Data->[%s]".format(time.clock(), data_toPrint))
                # Check Rx contents
                if waitingForConsoleCommand:
                    Rx = False
                    messageToSend = 'MD0'
                    if MessageFromSerial == '':
                        responseToServer = 'Error: Time Out'
                    else:
                        responseToServer = MessageFromSerial[:-2]
                    logging.info('Console Command Response: %s', responseToServer)
                    waitingForConsoleCommand = False
                    apiClient.Command = False
                elif MessageFromSerial[3] == 'Z':
                    Rx = False
                    messageToSend = 'MD0'
                    logging.info('Configured! %s', MessageFromSerial)
                elif MessageFromSerial[3] == 'D':
                    Rx = False
                    messageToSend = 'M1'
                    _39 = MessageFromSerial[5:]
                elif MessageFromSerial[3] == '1':
                    Rx = False
                    messageToSend = 'M2'
                    _38 = ""
                    _38 = MessageFromSerial[12:-2]
                elif MessageFromSerial[3] == '2':
                    Rx = False
                    messageToSend = 'M3'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '3':
                    Rx = False
                    messageToSend = 'M4'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '4':
                    Rx = False
                    messageToSend = 'M5'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '5':
                    Rx = False
                    messageToSend = 'M6'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '6':
                    Rx = False
                    messageToSend = 'M7'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '7':
                    Rx = False
                    messageToSend = 'M8'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '8':
                    Rx = False
                    messageToSend = 'MD0'
                    _38 = _38 + MessageFromSerial[4:-2]
                else:
                    errorCleanUp(MessageFromSerial)

            except serial.SerialException as e:
                errorCleanUp(e)

            except IndexError as i:
                errorCleanUp(i)
Ejemplo n.º 15
0
def setup_feeder():
    global feeder
    sys.stdout.write("[+] Starting feeder... \t\t")
    feeder = Feeder.new_feeder(MODULELIST, ENDPOINT)
    feeder.start()
    sys.stdout.write("Done!\n")
Ejemplo n.º 16
0
#!/usr/bin/env python3
import Feeder, MenuRenderer

feedurls = []

try:
    with open('rss.txt', 'r') as file:
        for line in file.readlines():
            line = line.strip()
            if line:
                feedurls.append(line)
except FileNotFoundError:
    print("Cannot find `rss.txt` file in this directory! Creating one...")
    with open("rss.txt", 'w') as file:
        file.write("")
    exit()

feeder = Feeder.Feeder(feedurls)

options = feeder.getTitles()

menu = MenuRenderer.MenuRenderer("Select RSS to Show", options)

selected = menu.run()

print("\nAll Feeds in this topic:\n\n")
for feed in feeder.getFeedsByIndex(selected):
    print(feed.title, ":")
    print('\t', feed.link)
    print('\n\t', feed.summary, '\n')
Ejemplo n.º 17
0
def SendCommand():
    global tenSec, Rx, messageToSend, errorCounter, _38, _39, responseToServer

    serialId = str(uuid.uuid4())
    data_toPrint = "serialComs: serialComs Thread Running ..."

    logging.info("TxST: SendCommand Thread Running ...")

    port.flushOutput()

    waitingForConsoleCommand = False

    while True:
        # Feed Watchdog Server
        Feeder.feeder(serialId, data_toPrint)

        if apiClient.Command:
            command = apiClient.G4Command + "\x0D"
            waitingForConsoleCommand = True
            Rx = True
        elif messageToSend == 'Config':
            command = "00SZ50132\x0D"
            Rx = True
        elif messageToSend == 'MD0':
            command = "00MD0\x0D"
            Rx = True
        elif messageToSend == 'M1':
            command = "00M1\x0D"
            Rx = True
        elif messageToSend == 'M2':
            command = "00M2\x0D"
            Rx = True
        elif messageToSend == 'M3':
            command = "00M3\x0D"
            Rx = True
        elif messageToSend == 'M4':
            command = "00M4\x0D"
            Rx = True
        elif messageToSend == 'M5':
            command = "00M5\x0D"
            Rx = True
        elif messageToSend == 'M6':
            command = "00M6\x0D"
            Rx = True
        elif messageToSend == 'M7':
            command = "00M7\x0D"
            Rx = True
        elif messageToSend == 'M8':
            command = "00M8\x0D"
            Rx = True

        data_toPrint = command[:-1]
        logging.debug("[%s]TxST: Tx Data->[%s]".format(time.clock(),
                                                       data_toPrint))
        port.write(command)
        while Rx:
            try:
                MessageFromSerial = port.readline()
                # Remove last 3 chars (CR LF)
                data_toPrint = MessageFromSerial[:-2]
                logging.debug("[%s]RxST: Rx Data->[%s]".format(
                    time.clock(), data_toPrint))
                # Check Rx contents
                if waitingForConsoleCommand:
                    Rx = False
                    messageToSend = 'MD0'
                    if MessageFromSerial == '':
                        responseToServer = 'Error: Time Out'
                    else:
                        responseToServer = MessageFromSerial[:-2]
                    logging.info('Console Command Response: %s',
                                 responseToServer)
                    waitingForConsoleCommand = False
                    apiClient.Command = False
                elif MessageFromSerial[3] == 'Z':
                    Rx = False
                    messageToSend = 'MD0'
                    logging.info('Configured! %s', MessageFromSerial)
                elif MessageFromSerial[3] == 'D':
                    Rx = False
                    messageToSend = 'M1'
                    _39 = MessageFromSerial[5:]
                elif MessageFromSerial[3] == '1':
                    Rx = False
                    messageToSend = 'M2'
                    _38 = ""
                    _38 = MessageFromSerial[12:-2]
                elif MessageFromSerial[3] == '2':
                    Rx = False
                    messageToSend = 'M3'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '3':
                    Rx = False
                    messageToSend = 'M4'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '4':
                    Rx = False
                    messageToSend = 'M5'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '5':
                    Rx = False
                    messageToSend = 'M6'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '6':
                    Rx = False
                    messageToSend = 'M7'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '7':
                    Rx = False
                    messageToSend = 'M8'
                    _38 = _38 + MessageFromSerial[4:-2]
                elif MessageFromSerial[3] == '8':
                    Rx = False
                    messageToSend = 'MD0'
                    _38 = _38 + MessageFromSerial[4:-2]
                else:
                    errorCleanUp(MessageFromSerial)

            except serial.SerialException as e:
                errorCleanUp(e)

            except IndexError as i:
                errorCleanUp(i)
Ejemplo n.º 18
0
def updateServer():

    global G4Command, Command

    apiId = str(uuid.uuid4())
    data_toPrint = "updateServer: updateServer Thread Running ..."

    while True:

        # Update Data
        time.sleep(2.5)
        UpdateStateData = myXML.parse('/home/pi/api/XMLs/UpdateStateData.xml')

        try:

            Automatic = UpdateStateData.getroot().find('Automatic')
            Automatic.text = Petrolog.getAutomaticStatus()

            Efficiency = UpdateStateData.getroot().find('Efficiency')
            if int(Petrolog.getTodayRuntimePercent()) < 100:
                Efficiency.text = Petrolog.getTodayRuntimePercent()
            else:
                Efficiency.text = '100'


            KickoffCount = UpdateStateData.getroot().find('KickoffCount')
            KickoffCount.text = Petrolog.getKickoffCount()

            MessageNumber = UpdateStateData.getroot().find('MessageNumber')
            MessageNumber.text = Petrolog.getMessageNumber()

            NoLoad = UpdateStateData.getroot().find('NoLoad')
            NoLoad.text = Petrolog.getNoLoad()

            NoPosition = UpdateStateData.getroot().find('NoPosition')
            NoPosition.text = Petrolog.getNoPosition()

            PercentFillage = UpdateStateData.getroot().find('PercentFillage')
            PercentFillage.text = Petrolog.getPercentFillage()

            PercentFillageSetting = UpdateStateData.getroot().find('PercentFillageSetting')
            PercentFillageSetting.text = Petrolog.getPercentFillageSetting()

            PumpOff = UpdateStateData.getroot().find('PumpOff')
            PumpOff.text = Petrolog.getPumpOff()

            SecondsToNextStart = UpdateStateData.getroot().find('SecondsToNextStart')
            SecondsToNextStart.text = Petrolog.getSecondsToNextStart()

            SignalStrength = UpdateStateData.getroot().find('SignalStrength')
            SignalStrength.text = Petrolog.getSignalStrength()

            StrokesLastCycle = UpdateStateData.getroot().find('StrokesLastCycle')
            StrokesLastCycle.text = Petrolog.getStrokesLastCycle()

            StrokesThisCycle = UpdateStateData.getroot().find('StrokesThisCycle')
            StrokesThisCycle.text = Petrolog.getStrokesThisCycle()

            TimeOut = UpdateStateData.getroot().find('TimeOut')
            TimeOut.text = Petrolog.getTimeOut()

            WellStatus = UpdateStateData.getroot().find('WellStatus')
            WellStatus.text = Petrolog.getWellStatus()

        except ValueError:
            logging.error('State Data Update - Serial communications failure')

        req = urllib2.Request(url='http://petrolog.intelectix.com/api/state',
                              data=myXML.tostring(UpdateStateData.getroot()),
                              headers={'Content-Type':'text/xml',
                                       'Authorization':'DeviceNumber=1943,ApiKey=UGV0cm9sb2dDbGllbnRl'})
        try:
            resp = urllib2.urlopen(req)
        except URLError as e:
            logging.warning('State Data Update - Failed to open connection to server! Error = %s', e.reason)
        else:
            r = resp.read()
            respuesta = myXML.ElementTree(myXML.fromstring(r))
            if respuesta.getroot().getiterator()[3].text == 'true':
                # Feed Watchdog Server only if request OK
                Feeder.feeder(apiId, data_toPrint)

        # Update Graph
        time.sleep(2.5)
        GraphData = myXML.parse('/home/pi/api/XMLs/GraphData.xml')
        points = GraphData.getroot().find("Points")

        dyna = Petrolog.getDyna()
        if dyna != '':
            for p in dyna:
                points.append(
                    point.fromstring(
                        '<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">'
                         +str(p[0])+','+str(p[1])+'</string>'))
            try:
                tempDyna = myXML.tostring(GraphData.getroot())
                req = urllib2.Request(url='http://petrolog.intelectix.com/api/graph',
                                      data=tempDyna,
                                      headers={'Content-Type':'text/xml',
                                               'Authorization':'DeviceNumber=1943,ApiKey=UGV0cm9sb2dDbGllbnRl'})
                try:
                    urllib2.urlopen(req)
                except URLError as e:
                    logging.warning('Dyna Update - Failed to open connection to server! Error = %s', e.reason)
            except IndexError:
                logging.warning('Dyna Update - Empty XML')

        # Command Pending?
        time.sleep(2.5)
        req = urllib2.Request(url='http://petrolog.intelectix.com/api/command',
                                      headers={'Content-Type':'text/xml',
                                               'Authorization':'DeviceNumber=1943,ApiKey=UGV0cm9sb2dDbGllbnRl'})
        try:
            resp = urllib2.urlopen(req)
            s = resp.read()
            respuesta = myXML.ElementTree(myXML.fromstring(s))

            commands = respuesta.iter(tag='Command')
            for command in commands:
                print 'Command from server: '+command.text
                Command = True
                G4Command = command.text
            commandsIds = respuesta.iter(tag='ConsoleCommandId')
            for commandId in commandsIds:
                print 'Command ID: '+commandId.text
                id = commandId.text
                while Petrolog.responseToServer == '':
                    time.sleep(.01)
                req = urllib2.Request(url='http://petrolog.intelectix.com/api/command',
                                             data='<CommandResponse>'
                                                        '<ConsoleCommandId>'
                                                            +id+
                                                        '</ConsoleCommandId>'
                                                        '<Response>'
                                                            +Petrolog.responseToServer+
                                                        '</Response>'
                                                  '</CommandResponse>',
                                             headers={'Content-Type':'text/xml',
                                                      'Authorization':'DeviceNumber=1943,ApiKey=UGV0cm9sb2dDbGllbnRl'})

                Petrolog.responseToServer = ''
                urllib2.urlopen(req)

        except URLError as e:
            logging.warning('Console Command - Failed to open connection to server! Error = %s', e.reason)
Ejemplo n.º 19
0
def updateServer():

    global G4Command, Command

    apiId = str(uuid.uuid4())
    data_toPrint = "updateServer: updateServer Thread Running ..."

    while True:

        # Update Data
        time.sleep(2.5)
        UpdateStateData = myXML.parse('/home/pi/api/XMLs/UpdateStateData.xml')

        try:

            Automatic = UpdateStateData.getroot().find('Automatic')
            Automatic.text = Petrolog.getAutomaticStatus()

            Efficiency = UpdateStateData.getroot().find('Efficiency')
            if int(Petrolog.getTodayRuntimePercent()) < 100:
                Efficiency.text = Petrolog.getTodayRuntimePercent()
            else:
                Efficiency.text = '100'

            KickoffCount = UpdateStateData.getroot().find('KickoffCount')
            KickoffCount.text = Petrolog.getKickoffCount()

            MessageNumber = UpdateStateData.getroot().find('MessageNumber')
            MessageNumber.text = Petrolog.getMessageNumber()

            NoLoad = UpdateStateData.getroot().find('NoLoad')
            NoLoad.text = Petrolog.getNoLoad()

            NoPosition = UpdateStateData.getroot().find('NoPosition')
            NoPosition.text = Petrolog.getNoPosition()

            PercentFillage = UpdateStateData.getroot().find('PercentFillage')
            PercentFillage.text = Petrolog.getPercentFillage()

            PercentFillageSetting = UpdateStateData.getroot().find(
                'PercentFillageSetting')
            PercentFillageSetting.text = Petrolog.getPercentFillageSetting()

            PumpOff = UpdateStateData.getroot().find('PumpOff')
            PumpOff.text = Petrolog.getPumpOff()

            SecondsToNextStart = UpdateStateData.getroot().find(
                'SecondsToNextStart')
            SecondsToNextStart.text = Petrolog.getSecondsToNextStart()

            SignalStrength = UpdateStateData.getroot().find('SignalStrength')
            SignalStrength.text = Petrolog.getSignalStrength()

            StrokesLastCycle = UpdateStateData.getroot().find(
                'StrokesLastCycle')
            StrokesLastCycle.text = Petrolog.getStrokesLastCycle()

            StrokesThisCycle = UpdateStateData.getroot().find(
                'StrokesThisCycle')
            StrokesThisCycle.text = Petrolog.getStrokesThisCycle()

            TimeOut = UpdateStateData.getroot().find('TimeOut')
            TimeOut.text = Petrolog.getTimeOut()

            WellStatus = UpdateStateData.getroot().find('WellStatus')
            WellStatus.text = Petrolog.getWellStatus()

        except ValueError:
            logging.error('State Data Update - Serial communications failure')

        req = urllib2.Request(
            url='http://petrolog.intelectix.com/api/state',
            data=myXML.tostring(UpdateStateData.getroot()),
            headers={
                'Content-Type': 'text/xml',
                'Authorization':
                'DeviceNumber=1943,ApiKey=UGV0cm9sb2dDbGllbnRl'
            })
        try:
            resp = urllib2.urlopen(req)
        except URLError as e:
            logging.warning(
                'State Data Update - Failed to open connection to server! Error = %s',
                e.reason)
        else:
            r = resp.read()
            respuesta = myXML.ElementTree(myXML.fromstring(r))
            if respuesta.getroot().getiterator()[3].text == 'true':
                # Feed Watchdog Server only if request OK
                Feeder.feeder(apiId, data_toPrint)

        # Update Graph
        time.sleep(2.5)
        GraphData = myXML.parse('/home/pi/api/XMLs/GraphData.xml')
        points = GraphData.getroot().find("Points")

        dyna = Petrolog.getDyna()
        if dyna != '':
            for p in dyna:
                points.append(
                    point.fromstring(
                        '<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">'
                        + str(p[0]) + ',' + str(p[1]) + '</string>'))
            try:
                tempDyna = myXML.tostring(GraphData.getroot())
                req = urllib2.Request(
                    url='http://petrolog.intelectix.com/api/graph',
                    data=tempDyna,
                    headers={
                        'Content-Type':
                        'text/xml',
                        'Authorization':
                        'DeviceNumber=1943,ApiKey=UGV0cm9sb2dDbGllbnRl'
                    })
                try:
                    urllib2.urlopen(req)
                except URLError as e:
                    logging.warning(
                        'Dyna Update - Failed to open connection to server! Error = %s',
                        e.reason)
            except IndexError:
                logging.warning('Dyna Update - Empty XML')

        # Command Pending?
        time.sleep(2.5)
        req = urllib2.Request(
            url='http://petrolog.intelectix.com/api/command',
            headers={
                'Content-Type': 'text/xml',
                'Authorization':
                'DeviceNumber=1943,ApiKey=UGV0cm9sb2dDbGllbnRl'
            })
        try:
            resp = urllib2.urlopen(req)
            s = resp.read()
            respuesta = myXML.ElementTree(myXML.fromstring(s))

            commands = respuesta.iter(tag='Command')
            for command in commands:
                print 'Command from server: ' + command.text
                Command = True
                G4Command = command.text
            commandsIds = respuesta.iter(tag='ConsoleCommandId')
            for commandId in commandsIds:
                print 'Command ID: ' + commandId.text
                id = commandId.text
                while Petrolog.responseToServer == '':
                    time.sleep(.01)
                req = urllib2.Request(
                    url='http://petrolog.intelectix.com/api/command',
                    data='<CommandResponse>'
                    '<ConsoleCommandId>' + id + '</ConsoleCommandId>'
                    '<Response>' + Petrolog.responseToServer + '</Response>'
                    '</CommandResponse>',
                    headers={
                        'Content-Type':
                        'text/xml',
                        'Authorization':
                        'DeviceNumber=1943,ApiKey=UGV0cm9sb2dDbGllbnRl'
                    })

                Petrolog.responseToServer = ''
                urllib2.urlopen(req)

        except URLError as e:
            logging.warning(
                'Console Command - Failed to open connection to server! Error = %s',
                e.reason)