Skip to content

Commit

Permalink
Simplify code.
Browse files Browse the repository at this point in the history
- defaultdict to avoid initialising every entry up front
- Use struct.calcsize instead of copying the values.
- if x == 0: y = False: else y = True => y = bool(x)
- list[len(list)-1] => list[-1]
- math.pow(256, 1) => 0x08 etc.
- x = bytearray(); x.append(y); x.append(z) => x = bytearray([y, z])
- value = x; return value => return x
  • Loading branch information
bwduncan committed Dec 9, 2019
1 parent feec47b commit 035d266
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 53 deletions.
5 changes: 2 additions & 3 deletions src/emonhub.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import pprint
import glob
import os
from collections import defaultdict

import emonhub_setup as ehs
import emonhub_coder as ehc
Expand Down Expand Up @@ -87,9 +88,7 @@ def run(self):
signal.signal(signal.SIGINT, self._sigint_handler)

# Initialise thread restart counters
restart_count = {}
for I in self._interfacers.itervalues():
restart_count[I.name] = 0
restart_count = defaultdict(int)

# Until asked to stop
while not self._exit:
Expand Down
15 changes: 4 additions & 11 deletions src/emonhub_coder.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,9 @@


def check_datacode(datacode):
# Data types & sizes (number of bytes)
datacodes = {'b': '1', 'h': '2', 'i': '4', 'l': '4', 'q': '8', 'f': '4', 'd': '8',
'B': '1', 'H': '2', 'I': '4', 'L': '4', 'Q': '8', 'c': '1', '?': '1'}

# if datacode is valid return the data size in bytes
if datacode in datacodes:
return int(datacodes[datacode])
# if not valid return False
else:
try:
return struct.calcsize(datacode)
except struct.error:
return False


Expand Down Expand Up @@ -42,5 +36,4 @@ def encode(datacode, value):

#value = 60
#datacode = "b"
result = struct.unpack(e + b*s, struct.pack(e + datacode, value))
return result
return struct.unpack(e + b*s, struct.pack(e + datacode, value))
7 changes: 2 additions & 5 deletions src/interfacers/EmonHubSMASolarInterfacer.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,12 @@ def __init__(self, name, inverteraddress='', inverterpincode='0000', timeinverva
self._port = 1
self._nodeid = int(nodeid)

if packettrace == 0:
self._packettrace = False
else:
self._packettrace = True
self._packettrace = bool(packettrace)

self.MySerialNumber = bytearray([0x08, 0x00, 0xaa, 0xbb, 0xcc, 0xdd])

self._reset_packet_send_counter()
self._Inverters = None
self._Inverters = {}
#Duration in seconds
self._time_inverval = int(timeinverval)
self._InverterPasswordArray = SMASolar_library.encodeInverterPassword(self._inverterpincode)
Expand Down
28 changes: 11 additions & 17 deletions src/smalibrary/SMABluetoothPacket.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ def __str__(self):
return "I am an instance of SMABluetoothPacket"

def getLevel2Checksum(self):
return self.UnescapedArray[len(self.UnescapedArray) - 2] * 256 + self.UnescapedArray[len(self.UnescapedArray) - 3]
return (self.UnescapedArray[-2] << 8) + self.UnescapedArray[-3]

def lastByte(self):
return self.UnescapedArray[len(self.UnescapedArray) - 1]
return self.UnescapedArray[-1]

def getLevel2Payload(self):
skipendbytes = 0
Expand All @@ -23,9 +23,9 @@ def getLevel2Payload(self):
if self.lastByte() == 0x7e:
skipendbytes = 3

# FIXME This comment says to skip the first 3 bytes, but the code skips the *last* 3 bytes
# Skip the first 3 bytes, they are the command code 0x0001 and 0x7E start byte
l = len(self.UnescapedArray) - skipendbytes
return self.UnescapedArray[startbyte:l]
return self.UnescapedArray[startbyte:-skipendbytes]

This comment has been minimized.

Copy link
@stuartpittaway

stuartpittaway Sep 20, 2020

Contributor

This is the root cause of issue #128 , reverting the code to

        l = len(self.UnescapedArray) - skipendbytes
        return self.UnescapedArray[startbyte:l]

fixes the error.

The reverted code returns a packet of 89 bytes, but the new code returns zero bytes.


def pushRawByteArray(self, barray):
# Raw byte array
Expand Down Expand Up @@ -68,14 +68,14 @@ def pushEscapedByte(self, value):
previousUnescapedByte = 0

if len(self.RawByteArray) > 0:
previousUnescapedByte = self.RawByteArray[len(self.RawByteArray) - 1]
previousUnescapedByte = self.RawByteArray[-1]

# Store the raw byte as it was received into RawByteArray
self.RawByteArray.append(value)

# did we receive the escape char in previous byte?
if len(self.RawByteArray) > 0 and previousUnescapedByte == 0x7d:
self.UnescapedArray[len(self.UnescapedArray) - 1] = value ^ 0x20
self.UnescapedArray[-1] = value ^ 0x20
else:
# Unescaped array is same as raw array
self.UnescapedArray.append(value)
Expand All @@ -84,17 +84,15 @@ def sendPacket(self, btSocket):
l = btSocket.send(str(self.header) + str(self.SourceAddress) + str(self.DestinationAddress) + str(self.cmdcode) + str(self.RawByteArray))

def containsLevel2Packet(self):
if len(self.UnescapedArray) < 5:
return False

return (self.UnescapedArray[0] == 0x7e and
return (len(self.UnescapedArray) >= 5 and
self.UnescapedArray[0] == 0x7e and
self.UnescapedArray[1] == 0xff and
self.UnescapedArray[2] == 0x03 and
self.UnescapedArray[3] == 0x60 and
self.UnescapedArray[4] == 0x65)

def CommandCode(self):
return self.cmdcode[0] + (self.cmdcode[1] * 256)
return self.cmdcode[0] + (self.cmdcode[1] << 8)

def setCommandCode(self, byteone, bytetwo):
self.cmdcode = bytearray([byteone, bytetwo])
Expand All @@ -110,7 +108,7 @@ def TotalUnescapedPacketLength(self):
return len(self.UnescapedArray) + self.headerlength

def TotalRawPacketLength(self):
return self.header[1] + (self.header[2] * 256)
return self.header[1] + (self.header[2] << 8)

def TotalPayloadLength(self):
return self.TotalRawPacketLength() - self.headerlength
Expand All @@ -126,11 +124,7 @@ def __init__(self, length1, length2, checksum=0, cmd1=0, cmd2=0, SourceAddress=b
self.SourceAddress = SourceAddress
self.DestinationAddress = DestinationAddress

self.header = bytearray()
self.header.append(0x7e)
self.header.append(length1)
self.header.append(length2)
self.header.append(checksum)
self.header = bytearray([0x7e, length1, length2, checksum])

# Create our array to hold the payload bytes
self.RawByteArray = bytearray()
Expand Down
33 changes: 16 additions & 17 deletions src/smalibrary/SMANET2PlusPacket.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
# See LICENCE and README file for details

import array
import math
try:
from __builtin__ import long
except ImportError:
Expand Down Expand Up @@ -86,26 +85,26 @@ def getByte(self, offset):
return self.packet[offset]

def getTwoByte(self, offset):
value = self.packet[offset] * math.pow(256, 0)
value += self.packet[offset + 1] * math.pow(256, 1)
value = self.packet[offset]
value += self.packet[offset + 1] << 8
return long(value)

def getFourByteLong(self, offset):
value = self.packet[offset] * math.pow(256, 0)
value += self.packet[offset + 1] * math.pow(256, 1)
value += self.packet[offset + 2] * math.pow(256, 2)
value += self.packet[offset + 3] * math.pow(256, 3)
value = self.packet[offset]
value += self.packet[offset + 1] << 0x08
value += self.packet[offset + 2] << 0x10
value += self.packet[offset + 3] << 0x18
return long(value)

def getEightByte(self, offset):
return self.packet[offset] * math.pow(256, 0) \
+ self.packet[offset + 1] * math.pow(256, 1) \
+ self.packet[offset + 2] * math.pow(256, 2) \
+ self.packet[offset + 3] * math.pow(256, 3) \
+ self.packet[offset + 4] * math.pow(256, 4) \
+ self.packet[offset + 5] * math.pow(256, 5) \
+ self.packet[offset + 6] * math.pow(256, 6) \
+ self.packet[offset + 7] * math.pow(256, 7)
return self.packet[offset] \
+ (self.packet[offset + 1] << 0x08) \
+ (self.packet[offset + 2] << 0x10) \
+ (self.packet[offset + 3] << 0x18) \
+ (self.packet[offset + 4] << 0x20) \
+ (self.packet[offset + 5] << 0x28) \
+ (self.packet[offset + 6] << 0x30) \
+ (self.packet[offset + 7] << 0x38)

def getArray(self):
return self.packet
Expand Down Expand Up @@ -139,8 +138,7 @@ def getFragment(self):
return self.packet[24]

def getTwoByteuShort(self, offset):
value = self.packet[offset] * math.pow(256, 0) + self.packet[offset + 1] * math.pow(256, 1)
return value
return self.packet[offset] + (self.packet[offset + 1] << 8)

def errorCode(self):
return self.getTwoByteuShort(22)
Expand All @@ -151,6 +149,7 @@ def calculateFCS(self):
myfcs = (myfcs >> 8) ^ self.fcstab[(myfcs ^ bte) & 0xff]

myfcs ^= 0xffff
return myfcs

def pushByteArray(self, barray):
for bte in barray:
Expand Down

0 comments on commit 035d266

Please sign in to comment.