Skip to content

Commit

Permalink
Start work of making code compatible with python 3
Browse files Browse the repository at this point in the history
  • Loading branch information
mickeprag committed May 22, 2017
1 parent 7169e47 commit b8b5791
Show file tree
Hide file tree
Showing 28 changed files with 69 additions and 63 deletions.
2 changes: 1 addition & 1 deletion api/src/api/__init__.py
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-

from ApiManager import ApiManager, IApiCallHandler, apicall
from .ApiManager import ApiManager, IApiCallHandler, apicall
4 changes: 2 additions & 2 deletions base/src/base/Application.py
Expand Up @@ -10,7 +10,7 @@
import traceback
import signal
import sys
from Plugin import Plugin, PluginContext
from .Plugin import Plugin, PluginContext

class mainthread(object):
""".. py:decorator:: mainthread
Expand Down Expand Up @@ -256,4 +256,4 @@ def __nextTask(self):
finally:
self.__taskLock.release()

from SignalManager import SignalManager
from .SignalManager import SignalManager
4 changes: 2 additions & 2 deletions base/src/base/Configuration.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-

from Plugin import Plugin, PluginMeta
from Settings import Settings
from .Plugin import Plugin, PluginMeta
from .Settings import Settings
import logging

class configuration(object):
Expand Down
3 changes: 2 additions & 1 deletion base/src/base/Plugin.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-

import logging
from six import add_metaclass

class PluginContext(object):
def __init__(self):
Expand Down Expand Up @@ -87,8 +88,8 @@ def __call__(cls, *args, **kwargs):
self.__init__()
return self

@add_metaclass(PluginMeta)
class Plugin(object):
__metaclass__ = PluginMeta

public = False

Expand Down
4 changes: 2 additions & 2 deletions base/src/base/Settings.py
Expand Up @@ -4,11 +4,11 @@
import json
import logging
import time
from Application import Application
from .Application import Application
from configobj import ConfigObj
from threading import Timer
from board import Board
import ConfigParser
from six.moves.configparser import ConfigParser

class Settings(object):
_config = None
Expand Down
4 changes: 2 additions & 2 deletions base/src/base/SignalManager.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-

from Application import Application
from Plugin import IInterface, ObserverCollection, Plugin
from .Application import Application
from .Plugin import IInterface, ObserverCollection, Plugin
import sys, types

class ISignalObserver(IInterface):
Expand Down
10 changes: 5 additions & 5 deletions base/src/base/__init__.py
@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-


from Application import Application, mainthread
from Configuration import configuration, ConfigurationValue, ConfigurationDict, ConfigurationList, ConfigurationNumber, ConfigurationString, ConfigurationManager
from Plugin import IInterface, Plugin, PluginContext, ObserverCollection, implements
from Settings import Settings
from SignalManager import ISignalObserver, SignalManager, signal, slot
from .Application import Application, mainthread
from .Configuration import configuration, ConfigurationValue, ConfigurationDict, ConfigurationList, ConfigurationNumber, ConfigurationString, ConfigurationManager
from .Plugin import IInterface, Plugin, PluginContext, ObserverCollection, implements
from .Settings import Settings
from .SignalManager import ISignalObserver, SignalManager, signal, slot
2 changes: 1 addition & 1 deletion board/desktop/board/__init__.py
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-

from Board import Board
from .Board import Board
2 changes: 1 addition & 1 deletion board/setup.py
Expand Up @@ -8,7 +8,7 @@
import os

if 'HWBOARD' not in os.environ:
print 'HWBOARD environmental variable not set'
print('HWBOARD environmental variable not set')
quit(1)

setup(
Expand Down
2 changes: 1 addition & 1 deletion developer/src/developer/__init__.py
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-

from Developer import Developer
from .Developer import Developer
2 changes: 1 addition & 1 deletion live/src/tellduslive/base/LiveMessage.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-

import hashlib
from LiveMessageToken import *
from .LiveMessageToken import LiveMessageToken

class LiveMessage():
def __init__(self, name = ""):
Expand Down
10 changes: 5 additions & 5 deletions live/src/tellduslive/base/LiveMessageToken.py
Expand Up @@ -2,25 +2,26 @@

import base64
import logging
import six

class LiveMessageToken(object):
TYPE_INVALID, TYPE_INT, TYPE_STRING, TYPE_BASE64, TYPE_LIST, TYPE_DICTIONARY = range(6)
TYPE_INVALID, TYPE_INT, TYPE_STRING, TYPE_BASE64, TYPE_LIST, TYPE_DICTIONARY = list(range(6))

def __init__(self, value = None):
self.valueType = LiveMessageToken.TYPE_INVALID
self.stringVal = u''
self.intVal = 0
self.dictVal = {}
self.listVal = []
if (type(value) is int or type(value) is long):
if (type(value) in six.integer_types):
self.valueType = self.TYPE_INT
self.intVal = value

elif (type(value) is bool):
self.valueType = self.TYPE_INT
self.intVal = int(value)

elif (type(value) is str or type(value) is unicode):
elif (type(value) in six.string_types):
self.valueType = self.TYPE_STRING
self.stringVal = value

Expand Down Expand Up @@ -94,7 +95,7 @@ def toByteArray(self):
retval = retval + LiveMessageToken(str(key)).toByteArray() + self.dictVal[key].toByteArray()
return retval + 's'

if type(self.stringVal) == unicode:
if six.PY2 and type(self.stringVal) == unicode:
s = base64.b64encode(self.stringVal.encode('utf-8'))
return 'u%X:%s' % (len(s), str(s),)

Expand Down Expand Up @@ -167,4 +168,3 @@ def parseToken(string, start):
token.valueType = LiveMessageToken.TYPE_STRING

return (start, token)

6 changes: 3 additions & 3 deletions live/src/tellduslive/base/ServerConnection.py
@@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-

import socket, ssl, errno, select, logging
from LiveMessage import LiveMessage
from .LiveMessage import LiveMessage
from base import Settings

class ServerConnection(object):
CLOSED, CONNECTING, CONNECTED, READY, MSG_RECEIVED, DISCONNECTED = range(6)
CLOSED, CONNECTING, CONNECTED, READY, MSG_RECEIVED, DISCONNECTED = list(range(6))

def __init__(self):
self.publicKey = ''
Expand Down Expand Up @@ -122,7 +122,7 @@ def _readSSL(self):
if (len(data) < buffSize):
hasMoreData = False
resp += data
except ssl.SSLError, e:
except ssl.SSLError as e:
if e.args[0] == ssl.SSL_ERROR_WANT_READ:
pass
else:
Expand Down
7 changes: 4 additions & 3 deletions live/src/tellduslive/base/ServerList.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-

import httplib, logging, time
import logging, time
from six.moves import http_client
import netifaces
import xml.parsers.expat
from board import Board
Expand All @@ -27,7 +28,7 @@ def popServer(self):
return self.list.pop(0)

def retrieveServerList(self):
conn = httplib.HTTPConnection('%s:80' % Board.liveServer())
conn = http_client.HTTPConnection('%s:80' % Board.liveServer())
conn.request('GET', "/server/assign?protocolVersion=3&mac=%s" % ServerList.getMacAddr(Board.networkInterface()))
response = conn.getresponse()

Expand All @@ -46,6 +47,6 @@ def getMacAddr(ifname):
addrs = netifaces.ifaddresses(ifname)
try:
mac = addrs[netifaces.AF_LINK][0]['addr']
except IndexError, KeyError:
except (IndexError, KeyError) as e:
return ''
return mac.upper().replace(':', '')
22 changes: 11 additions & 11 deletions live/src/tellduslive/base/TelldusLive.py
Expand Up @@ -5,9 +5,9 @@

from base import Application, Settings, IInterface, ObserverCollection, Plugin, mainthread
from board import Board
from ServerList import *
from ServerConnection import ServerConnection
from LiveMessage import *
from .ServerList import *
from .ServerConnection import ServerConnection
from .LiveMessage import *

class ITelldusLiveObserver(IInterface):
def liveConnected():
Expand All @@ -21,7 +21,7 @@ class TelldusLive(Plugin):
observers = ObserverCollection(ITelldusLiveObserver)

def __init__(self):
print("Telldus Live! loading")
logging.info("Telldus Live! loading")
self.email = ''
self.supportedMethods = 0
self.connected = False
Expand All @@ -45,7 +45,7 @@ def handleMessage(self, message):
self.registered = False
params = message.argument(0).dictVal
self.s['uuid'] = params['uuid'].stringVal
print("This client isn't activated, please activate it using this url:\n%s" % params['url'].stringVal)
logging.info("This client isn't activated, please activate it using this url:\n%s", params['url'].stringVal)
self.observers.liveConnected()
return

Expand Down Expand Up @@ -80,7 +80,7 @@ def handleMessage(self, message):
f(o, message)
handled = True
if not handled:
print "Did not understand: %s" % message.toByteArray()
logging.warning("Did not understand: %s", message.toByteArray())

def isConnected(self):
return self.connected
Expand All @@ -103,11 +103,11 @@ def run(self):
server = self.serverList.popServer()
if not server:
wait = random.randint(60, 300)
print("No servers found, retry in %i seconds" % wait)
logging.warning("No servers found, retry in %i seconds", wait)
continue
if not self.conn.connect(server['address'], int(server['port'])):
wait = random.randint(60, 300)
print("Could not connect, retry in %i seconds" % wait)
logging.warning("Could not connect, retry in %i seconds", wait)

elif state == ServerConnection.CONNECTED:
pongTimer, self.pingTimer = (time.time(), time.time())
Expand All @@ -122,14 +122,14 @@ def run(self):

elif state == ServerConnection.DISCONNECTED:
wait = random.randint(10, 50)
print("Disconnected, reconnect in %i seconds" % wait)
logging.warning("Disconnected, reconnect in %i seconds", wait)
self.__disconnected()

else:
if (time.time() - pongTimer >= 360): # No pong received
self.conn.close()
wait = random.randint(10, 50)
print("No pong received, disconnecting. Reconnect in %i seconds" % wait)
logging.warning("No pong received, disconnecting. Reconnect in %i seconds", wait)
self.__disconnected()
elif (time.time() - self.pingTimer >= 120):
# Time to ping
Expand Down Expand Up @@ -190,6 +190,6 @@ def getMacAddr(ifname):
addrs = netifaces.ifaddresses(ifname)
try:
mac = addrs[netifaces.AF_LINK][0]['addr']
except IndexError, KeyError:
except (IndexError, KeyError) as e:
return ''
return mac.upper().replace(':', '')
4 changes: 2 additions & 2 deletions live/src/tellduslive/base/__init__.py
@@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-

from TelldusLive import TelldusLive, ITelldusLiveObserver
from LiveMessage import LiveMessage
from .TelldusLive import TelldusLive, ITelldusLiveObserver
from .LiveMessage import LiveMessage
4 changes: 2 additions & 2 deletions live/src/tellduslive/web/WebRequestHandler.py
Expand Up @@ -40,7 +40,7 @@ def handleRequest(self, plugin, path, params, request, **kwargs):
if path == 'login':
try:
authrequest = oidconsumer.begin('http://login.telldus.com')
except consumer.DiscoveryFailure, exc:
except consumer.DiscoveryFailure as exc:
logging.error(str(exc[0]))
return None # TODO(micke): Error
sregRequest = sreg.SRegRequest(required=['fullname', 'email'])
Expand All @@ -57,7 +57,7 @@ def handleRequest(self, plugin, path, params, request, **kwargs):
return None # TODO(micke): Error
elif info.status == consumer.SUCCESS:
sregResp = sreg.SRegResponse.fromSuccessResponse(info)
data = dict(sregResp.items())
data = dict(list(sregResp.items()))
if 'email' not in data:
return None # TODO(micke): Error
tellduslive = TelldusLive(self.context)
Expand Down
2 changes: 1 addition & 1 deletion live/src/tellduslive/web/__init__.py
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-

from WebRequestHandler import WebRequestHandler
from .WebRequestHandler import WebRequestHandler
3 changes: 3 additions & 0 deletions log/src/log/Logger.py
Expand Up @@ -9,6 +9,9 @@ def __init__(self, stream):
self.buffer = ''
self.stream = stream

def flush(self):
pass

def write(self, data, *args, **kwargs):
if data == "\n":
if self.stream == 'stderr':
Expand Down
2 changes: 1 addition & 1 deletion log/src/log/__init__.py
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-

from Logger import Logger
from .Logger import Logger
4 changes: 2 additions & 2 deletions plugin-loader/src/pluginloader/Loader.py
Expand Up @@ -11,7 +11,7 @@
import threading
import time
import traceback
import urllib
from six.moves.urllib.parse import urlencode
import urllib2
import yaml
import zipfile
Expand Down Expand Up @@ -54,7 +54,7 @@ def infoObject(self):
'long_description': self.manifest.get('long_description', ''),
'description': self.manifest.get('description', ''),
'icon': '/pluginloader/icon?%s' %
urllib.urlencode({'name': self.name}) if self.icon != '' else '',
urlencode({'name': self.name}) if self.icon != '' else '',
'loaded': self.loaded,
'name': self.name,
'size': self.size(),
Expand Down
2 changes: 1 addition & 1 deletion run.py
Expand Up @@ -12,7 +12,7 @@
print("Loading plugin %s" % dist)
try:
pkg_resources.working_set.add(dist)
except Exception, e:
except Exception as e:
print("Could not load", dist, e)
for entry in pkg_resources.working_set.iter_entry_points('telldus.main'):
moduleClass = entry.load()
Expand Down
8 changes: 4 additions & 4 deletions telldus/src/telldus/DeviceApiManager.py
Expand Up @@ -2,8 +2,8 @@

from api import IApiCallHandler, apicall
from base import Plugin, implements
from Device import Device
from DeviceManager import DeviceManager
from .Device import Device
from .DeviceManager import DeviceManager

class DeviceApiManager(Plugin):
implements(IApiCallHandler)
Expand Down Expand Up @@ -149,7 +149,7 @@ def sensorsList(self, includeValues=None, includeScale=None, **kwargs):
sensor['battery'] = battery
if includeValues:
data = []
for sensorType, values in d.sensorValues().items():
for sensorType, values in list(d.sensorValues().items()):
for value in values:
if includeScale:
data.append({
Expand Down Expand Up @@ -177,7 +177,7 @@ def sensorInfo(self, id, **kwargs):
"""
device = self.__retrieveDevice(id)
sensorData = []
for sensorType, values in device.sensorValues().items():
for sensorType, values in list(device.sensorValues().items()):
for value in values:
sensorData.append({
'name': Device.sensorTypeIntToStr(sensorType),
Expand Down
2 changes: 1 addition & 1 deletion telldus/src/telldus/DeviceManager.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-

from Device import CachedDevice, DeviceAbortException
from .Device import CachedDevice, DeviceAbortException
import json, logging, time
from tellduslive.base import TelldusLive, LiveMessage, LiveMessageToken, ITelldusLiveObserver
from base import Application, Settings, ObserverCollection, IInterface, Plugin, implements, mainthread, signal
Expand Down

0 comments on commit b8b5791

Please sign in to comment.